Israel

Israel

  • 670
  • 1.3k
  • 213.8k

I do correct my code. But its still showing this error msg

Mar 21 2017 4:23 PM
Hi,
I need to save into my database. But I am still having the same error message:
Object reference not set to an instance of an object
 
see what I do first:
private void insert_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("insert into student(sno,sname,course,fee,photo) values(" + textBox1.Text + ",'" +
textBox2.TabIndex + "','" + textBox3.Text + "'," + textBox4.Text + ",@photo)", con);
conv_photo();
con.Open();// Here I wrote this and when I save I receive this message: Object reference not set to an instance of an object.
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("record inserted");
loaddata();
}
else
MessageBox.Show("insertion failed");
}
void conv_photo()
{
//converting photo to binary data
if (pictureBox1.Image != null)
{
//
//using MemoryStream:
ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] photo_aray = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_aray, 0, photo_aray.Length);
cmd.Parameters.AddWithValue("@photo", photo_aray);
 
Later when I change and write this its showing the same error message. What's wrong:
 
private void insert_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("insert into student(sno,sname,course,fee,photo) values(" + textBox1.Text + ",'" +
textBox2.TabIndex + "','" + textBox3.Text + "'," + textBox4.Text + ",@photo)", con);
conv_photo();
//con.Open();
if (con.State != ConnectionState.Open)
con.Open(); // same error message: Object reference not set to an instance of an object.
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("record inserted");
loaddata();
}
else
MessageBox.Show("insertion failed");
}
void conv_photo()
{
//converting photo to binary data
if (pictureBox1.Image != null)
{
//
//using MemoryStream:
ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] photo_aray = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_aray, 0, photo_aray.Length);
cmd.Parameters.AddWithValue("@photo", photo_aray);
}
 
 
 

Answers (9)