0

I am trying to insert image to the table [student] I have created in my Microsoft SQL Server.

Table student

I am using the FileUpload to upload the image, but I have problem with the code because my code always executes the catch block. Please help

try
{
    if (FileUpload1.HasFile)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = "Data Source=DESKTOP-H7KQUT1;Initial Catalog=SAOS;Integrated Security=True";

        string strname = FileUpload1.FileName.ToString();
        FileUpload1.PostedFile.SaveAs(Server.MapPath("~/upload/") + strname);

        con.Open();

        string insertQuery = "insert into student (SID, Email, Contact, FName, LName, HomeAddress, Gender, DOB, Image) values (@SID, @Email, @Contact, @FName, @LName, @HomeAddress, @Gender, @DOB, @Image)";
        SqlCommand cmd = new SqlCommand(insertQuery, con);

        cmd.Parameters.AddWithValue("@SID", TextBoxID.Text);
        cmd.Parameters.AddWithValue("@Email", TextBoxEmail.Text);
        cmd.Parameters.AddWithValue("@Contact", TextBoxContact.Text);
        cmd.Parameters.AddWithValue("@FName", TextBoxFName.Text);
        cmd.Parameters.AddWithValue("@LName", TextBoxLName.Text);
        cmd.Parameters.AddWithValue("@HomeAddress", TextBoxHome.Text);
        cmd.Parameters.AddWithValue("@Gender", DropDownListGender.SelectedItem.ToString());
        cmd.Parameters.AddWithValue("@DOB", TextBoxDOB.Text);
        cmd.Parameters.AddWithValue("@Image", FileUpload1.ToString());

        cmd.ExecuteNonQuery();
        con.Close();

        Label1.Visible = true;
        Label1.Text = "Image Uploaded successfully";
    }
    else
    {
        Label1.Visible = true;
        Label1.Text = "Plz upload the image!!!!";
    }
}
catch (Exception ex)
{
    MessageBox.Show("ex.Message");
}
3
  • Please update your catch block to be MessageBox.Show(ex.Message); (no quotes) and include the full exception details in your question. Commented Sep 18, 2018 at 17:31
  • 1
    You need to add the exception details to your question. Commented Sep 18, 2018 at 17:33
  • 2
    Check this: stackoverflow.com/questions/21601858/… Commented Sep 18, 2018 at 17:33

1 Answer 1

0

if you store image in sql server as blob or image format you should send is as byte array.

int imglength = FileUpload1.PostedFile.ContentLength;
byte[] bytearray = new byte[imglength];
cmd.Parameters.AddWithValue("@image", bytearray);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.