Tuesday, January 17, 2012

Catching SQLException in C#.Net


Catching SQLException in C#.Net :

Example : 



    public void InsertAttendance()
    {
        try
        {
            using (SqlConnection Con = new SqlConnection("ConnectionString"))
            {
                SqlCommand InserCmd = new SqlCommand();
                InserCmd.Connection = Con;
                InserCmd.CommandType = CommandType.StoredProcedure;
                InserCmd.CommandText = "SP_Name";


                Con.Open();
                InserCmd.ExecuteNonQuery();
                Con.Close();
            }
        }
        catch (SqlException SqlEx)
        {
            StringBuilder ErrorText = new StringBuilder();


            ErrorText.Append("Errors Count : " + SqlEx.Errors.Count + "<BR />");


            foreach (SqlError DBInsertErr in SqlEx.Errors)
            {
                ErrorText.Append("Error No. " + DBInsertErr.Number + " - " + DBInsertErr.Message + "<BR />");
            }


            Response.Write(ErrorText.ToString());
        }


        catch (Exception Ex)
        {
            Response.Write(ErrorText.ToString());
        }


    }

No comments:

Post a Comment