I am getting the error while inserting the image from win-form.Can anyone please tell me the in the code.I am using Visual Studio 2013 and MS Sql 2008 R2.
Thanks .
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection("Data Source=(local);Initial Catalog=maria;Persist Security Info=True;User ID=sa;Password=123456");
SqlCommand command;
string imgLoc = "";
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "jpeg|*.jpg|bmp|*.bmp|all files|*.*";
dlg.Title = "Select Employee Picture";
if (dlg.ShowDialog() == DialogResult.OK)
{
imgLoc = dlg.FileName.ToString();
pictureBox1.ImageLocation = imgLoc;
}
}
catch (Exception)
{
MessageBox.Show("Please enter the valid image.");
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
byte[] img = null;
FileStream fs = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
string sql = "INSERT INTO STU(EID,FIRST_NAME,LAST_NAME,IMAGE)VALUES(" + textBox1.Text + "," + textBox2.Text + "," + textBox3.Text + ",@img)";
if (cn.State != ConnectionState.Open)
cn.Open();
command = new SqlCommand(sql, cn);
command.Parameters.Add(new SqlParameter("@img", img));
command.ExecuteNonQuery();
cn.Close();
MessageBox.Show(ToString() + "Record(s) Saved.");
}
catch (Exception)
{
cn.Close();
MessageBox.Show("Insertion Failed");
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string sql = "SELECT FIRST_NAME,LAST_NAME,IMAGE FROM STU WHERE Id=" + textBox1.Text + "";
cn.Open();
command = new SqlCommand(sql, cn);
SqlDataReader reader = command.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
textBox2.Text = reader[0].ToString();
textBox3.Text = reader[1].ToString();
byte[] img = (byte[])(reader[2]);
if (img == null)
pictureBox1.Image = null;
else
{
MemoryStream ms=new MemoryStream(img);
pictureBox1.Image=Image.FromStream(ms);
}
}
else
{
MessageBox.Show("Id Doesnot exists");
}
cn.Close();
}
catch(Exception)
{
cn.Close();
MessageBox.Show("Id Does not Exists.");
}
}
}
}