User665608656 posted
Hi jsshivalik,
According to your description, if you want to display the error message, you can use try-catch-finally grammar: try-catch-finally (C# Reference)
I have made an example , you could refer to the following code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
try
{
SqlCommand cmd = new SqlCommand("Insert into Test (Id,Name) values(@Id,@Name)", conn);
cmd.Parameters.AddWithValue("@Id", txtId.Text);
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.ExecuteNonQuery();
fpUpload.SaveAs(Server.MapPath("~") + "/Attachment/" + nFile);
StringBuilder builder = new StringBuilder();
builder.Append("<script language=JavaScript>alert(\"Successsfully Done!\")</script>");
Page.ClientScript.RegisterStartupScript(this.GetType(), "SuccessAlert", builder.ToString());
}
catch (Exception ex)
{
StringBuilder builder = new StringBuilder();
builder.Append("<script language=JavaScript>");
builder.Append("alert(\"" + ex.Message.Replace("\r\n", "") + "\")");
builder.Append("</script>");
Page.ClientScript.RegisterStartupScript(this.GetType(), "FailAlert", builder.ToString());
}
finally
{
conn.Close();
txtId.Text = "";
txtName.Text = "";
}
}
The result of this work demo:

Best Regards,
YongQing.