Home All Groups Group Topic Archive Search About

statechange event in code

Author
18 Jan 2006 7:31 AM
Ant
Hi,

If i have a design time connection object, I can click the objects
statechange event & write code in the event handler to respond to the event
being changed. No problems.

However, if I create a coded conenction object in the click event of a
button, & create an event & delegate within that same button click event:

mySQLConObj.StateChange +=new StateChangeEventHandler(methodToHandle);

& write code in the methodToHandle event, it doesn't work.

Where in code can I put the statechange event & the delegate attached to it
in code? Or must i move the connection object out of the click button method
to do this? If so, where?


Thanks for any thoughts on this.

Regards
Ant

Author
18 Jan 2006 8:43 PM
Jesús López
StateChange event works. The error is in the code that you are not showing.

Regards

Jesús López
MVP
Author
19 Jan 2006 1:26 AM
Ant
Hello Jesus, thanks for the reply.

I've worked it out. Below is the code. It turned out that the event change
handler & delegate will only work if it is placed before opening the
connection, no after it. For example:

private void button2_Click(object sender, System.EventArgs e)
{
  string connectionString = "Initial catalog = Northwind";

  SqlConnection con = new SqlConnection(connectionString);


  // Will work here
  con.StateChange +=new StateChangeEventHandler(con_StateChange);

  con.Open();


// Wont work here
con.StateChange +=new StateChangeEventHandler(con_StateChange);

}

  private void con_StateChange(object sender, StateChangeEventArgs e)
{
MessageBox.Show("The state is now " + e.CurrentState.ToString());
}

Thank you.




Show quote
"Jesús López" wrote:

> StateChange event works. The error is in the code that you are not showing.
>
> Regards
>
> Jesús López
> MVP
>
>
>
Author
19 Jan 2006 4:53 PM
Jesús López
This is the expected behavior. All events work the same in .NET. An event
handler will begin being called after it is attached to the event. Never
before.

Regards:

Jesús López
VB MVP

AddThis Social Bookmark Button