Connection event : SqlConnection : ADO.Net C# Examples


C# Examples » ADO.Net » SqlConnection »

 

Connection event









    
using  System;
using  System.Drawing;
using  System.Collections;
using  System.ComponentModel;
using  System.Windows.Forms;
using  System.Data;
using  System.Data.SqlClient;

public  class  MainClass{
      public  static  void  Main(){
        SqlConnection  cn  =  new  SqlConnection();

        try
        {
            cn.StateChange  +=  new  StateChangeEventHandler(StateChange);
            cn.InfoMessage  +=  new  SqlInfoMessageEventHandler(InfoMessage);

            cn.ConnectionString  =  "server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated  Security=SSPI;";
            cn.Open();
            cn.ChangeDatabase("Biblio");

        }
        catch(  Exception  ex  )
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            //  Unsubscribe  from  the  Events  we  subscribed  to.
            cn.StateChange  -=  new  StateChangeEventHandler(StateChange);
            cn.InfoMessage  -=  new  SqlInfoMessageEventHandler(InfoMessage);
        }
      }
    private  static  void  StateChange(object  sender,  System.Data.StateChangeEventArgs  e)
    {
        Console.WriteLine("State  was:"  +  e.OriginalState.ToString()  +  ".  New  state  =  "  +  e.CurrentState.ToString()  );
    }
    
    private  static  void  InfoMessage(  object  sender,  System.Data.SqlClient.SqlInfoMessageEventArgs  e)
    {
        int  i;
        for  (i=0;  i  <  e.Errors.Count;  i++  )
        {
            Console.WriteLine(e.Errors[i].Message);
        }
    }

}
    
   
  
   



Output

State was:Closed. New state = Open
Could not locate entry in sysdatabases for database 'Biblio'. No entry found with that name. Make su
re that the name is entered correctly.


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo ADO.Net
» SqlConnection