title: Check if record inserted successfully
body: <p>The code here inserts data into a SQL Server table and it works fine but I could not know if that process was successfully or not. The code here shows error and it does not work as expected. How to use try and catch to check if data inserted or not. </p>
  
  <p>Code </p>
  
  <pre><code>protected void btSave_Click(object sender, EventArgs e)
  {
      SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
  
      try
      {
          string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
          string contentType = FileUpload1.PostedFile.ContentType;
  
          using (Stream fs = FileUpload1.PostedFile.InputStream)
          {
              using (BinaryReader br = new BinaryReader(fs))
              {
                  byte[] bytes = br.ReadBytes((Int32)fs.Length);
                  string constr = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
  
                  con.Open();
                  string query = "insert into events (comName,eventName, eventDis, eventDate,  fName, contentType, Data) values (@comName,@eventName,@eventDis, @eventDate,@fName, @contentType, @Data)";
  
                  using (SqlCommand cmd = new SqlCommand(query))
                  {
                      cmd.Connection = con;
                      cmd.Parameters.AddWithValue("@comName", txtcname.Text);
                      cmd.Parameters.AddWithValue("@eventName", txtename.Text);
                      cmd.Parameters.AddWithValue("@eventDis", txteDis.Text);
                      cmd.Parameters.AddWithValue("@eventDate", txteDate.Text);
                      cmd.Parameters.AddWithValue("@fName", filename);
                      cmd.Parameters.AddWithValue("@ContentType", contentType);
                      cmd.Parameters.AddWithValue("@Data", bytes);
  
                      cmd.ExecuteNonQuery();
  
                      con.Close();
                  }
              }
          }
      }
      catch (SqlException ex)
      {
          return"Data not inserted !" + ex;
      }
  }
  </code></pre>