Loop through all errors : SqlException : ADO.Net C# Examples


C# Examples » ADO.Net » SqlException »

 

Loop through all errors









    
using  System;
using  System.Data;
using  System.Data.SqlClient;

class  MainClass
{
      static  void  Main()
      {
                  SqlConnection  conn  =  new  SqlConnection(@"data  source  =  .\sqlexpress;integrated  security  =  true;database  =  northwnd");

                  SqlCommand  cmd  =  conn.CreateCommand();
                  cmd.CommandType  =  CommandType.StoredProcedure;
                  cmd.CommandText  =  "error  command";

                  try
                  {
                        conn.Open();
                        cmd.ExecuteNonQuery();
                  }
                  catch  (System.Data.SqlClient.SqlException  ex)
                  {
                        for  (int  i  =  0;  i  <  ex.Errors.Count;  i++)
                        {
                                  Console.WriteLine("Index  #"  +  i);
                                  Console.WriteLine("Exception:  "  +  ex.Errors[i].ToString()  );
                                  Console.WriteLine("Number:  "  +  ex.Errors[i].Number.ToString()  );
                        }
                  }
                  catch  (System.Exception  ex)
                  {
                        Console.WriteLine("Source:  "  +  ex.Source);
                        Console.WriteLine("Exception  Message:  "  +  ex.Message);
                  }
                  finally
                  {
                        if  (conn.State  ==  ConnectionState.Open)
                        {
                              Console.WriteLine("Finally  block  closing  the  connection");
                              conn.Close();
                        }
                  }
      }
}
    
   
  
   



Output

Index #0
Exception: System.Data.SqlClient.SqlError: Cannot open database "northwnd" requested by the login. T
he login failed.
Number: 4060
Index #1
Exception: System.Data.SqlClient.SqlError: Login failed for user 'navioo\Joe'.
Number: 18456


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo ADO.Net
» SqlException