Sir, I recently developed an address book application. When I try to update my address info if no new image is inserted the update query fails to execute.
private void Update_Click(object sender, EventArgs e)
{
if (txtfname.Text != "" && txtlname.Text != "")
{
try
{
// Read the Data From All fields
string fname = txtfname.Text;
string lname = txtlname.Text;
string house = txthouse.Text;
string city = txtcity.Text;
string country = txtcountry.Text;
string state = txtstate.Text;
string post = txtpost.Text;
string mail = txtmail.Text;
string blood = txtblood.Text;
string mobile = txtmobile.Text;
string dob = txtdob.Text;
byte[] imagedata = ReadFile(path.Text);
SqlConnection con = new SqlConnection(conn);
//update query
string query = "UPDATE address SET firstname ='" + fname + "',lastname='" + lname + "',house='" + house + "',city='" + city + "',country='" + country + "',state='" + state + "',post='" + post + "',mail='" + mail + "',blood='" + blood + "',mobile='" + mobile + "',dob='" + dob + "',image=@image WHERE (firstname ='" + fname + "' AND lastname='" + lname + "')";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("@image", (object)imagedata));
con.Open();
int i;
i = cmd.ExecuteNonQuery();
if (i == 1)
{
rInsert.Text = "Address Updated Sucessfully...!!!";
}
else
{
rInsert.Text = "Name not found in Database...!!!";
}
con.Close();
}
catch (Exception)
{
MessageBox.Show("Unable to Update...!!!", "Error occur", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Please Insert first name and last name"Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
//coverting image to bytes for storing in data base
byte[] ReadFile(string sPath)
{
//Initialize byte array with a null value initially.
byte[] data = null;
//Use FileInfo object to get file size.
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
//Open FileStream to read file
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
//Use BinaryReader to read file stream into byte array.
BinaryReader br = new BinaryReader(fStream);
//When you use BinaryReader, you need to supply number of bytes to read from file.
//In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes((int)numBytes);
return data;
}