2

I want to return error that occured at the time of update in SQL Server 2008.

Now I want to display this error to user so that he can understand what goes wrong.

How should I do this in c#?

Thanks.........

1
  • welcome to stackoverflow. please show some of your code. Commented Apr 30, 2011 at 12:11

3 Answers 3

4

Errors when performing an SQL statement against a database raise an exception in the connector. Those exceptions are of type SqlException and, as such, have a Message property that contains a user friendly description of the error.

Remember though that while user-friendly, this message is aimed at developers. You should not display that to an end-user.

As usual, to trap an exception you have to use a try-catch block:

try
{
    SqlConnection conn = null; 
    conn = new SqlConnection(connString);  // connstring is your connection string to the database
    conn.Open(); 

    var strSQLCommand = "SELECT* FROM TABLE";  // statement is wrong! will raise an exception
    var command = new SqlCommand(strSQLCommand, conn); 
    var ret = command.ExecuteScalar(); 

    conn.Close(); 

    return ret; 
}
catch (SqlException e)
{
    Console.WriteLine(e.Message);
}

This example of course assumes a Console application.

Sign up to request clarification or add additional context in comments.

Comments

1

try this

try
{
      //your sql code
}

catch(SqlException sqlEx)
{
    for (int i = 0; i < ex.Errors.Count; i++)
        {
            errorMessages.Append("Index #" + i + "\n" +
                "Message: " + ex.Errors[i].Message + "\n" +
                "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
                "Source: " + ex.Errors[i].Source + "\n" +
                "Procedure: " + ex.Errors[i].Procedure + "\n");
        }
        Console.WriteLine(errorMessages.ToString());
}

SqlException - which catches all the sql exception

Comments

0

Try using a try, catch clause

something like that:

try {
// Update Code Here
}
catch (Exception e) {
// Error message in e.Message
// On a form
   MessageBox.Show(e.Message, "Error!");
// TextBox text1 is defined
   text1.Text = e.Message;
   System.Console.WriteLine(e.Message);
}

where you can replace Exception with the type of exception you want to catch (SqlException).

2 Comments

i Want to display exception that sql returned
The e.Message is a string with the error in readable form. You can dispay it using a MessageBox.Show(e.Message) on a form or by asigning it to the Text value of an UI element like textbox or write it to the Console with System.Console.WriteLine(e.Message) etc.

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.