2
Answers

Error Handling in C# Asp.net

I am unsure how to error handle my code as I am new to coding and C#, however I would like to use a try catch to stop my program from crashing when the wrong ID is entered into to textbox. It is used to add a new property to the database however if you do not enter the correct landlord ID the system crashes. I would like a textbox to show saying the error and not the system to completely crash. This is my code for behind the button
  1. protected void btnLandlordSave_Click(object sender, EventArgs e)  
  2. {  
  3. //Creating a connection to my database using the connection string  
  4. string cs = System.Configuration.ConfigurationManager.ConnectionStrings["rent-dbConnectionString1"].ConnectionString;  
  5. SqlConnection con = new SqlConnection(cs);  
  6. //preparing a query which will insert the data entered in the textboxes to the database  
  7. SqlCommand cmd = new SqlCommand("INSERT INTO Properties(Landlord_Id, Property_Address, Property_Num_Of_Tenants, Property_Vacant) values('" + this.txtLandlordId.Text + "','" + this.txtPropertyAddress.Text + "','" + this.txtNumOfTenants.Text + "','" + this.chkVacant.Checked + "')", con);  
  8. con.Open();  
  9. cmd.ExecuteNonQuery();  
  10. con.Close();  
  11. Response.Redirect("LandlordIndex.aspx");  
  12. }
Answers (2)