Pages

Saturday, February 23, 2013

Passing Parameters to Events - C#

All right , again one post away from my favorite SharePoint world but this is kind of generic which can be used anywhere in C#.

Today we will see how we can pass some custom parameters to any event in C#.

Consider a scenario where you are calling some method asynchronously and execution is happening in loops.
In General, we register an event with the method which gets called after method call is completed. but as the asynchronous execution is happening in the loop , so in the on completed event you never know which for which call the execution has been completed.

Check out this sample scenario where I have a simple windows forms application with two buttons and label, both buttons are registered to a same on click event. Now say, on click of each button I want to perform some independent actions and also want to pass some parameters to the on click event. I know there can be many approaches to do this but I have just taken this example to prove the actual point of this blog post.


public Form1()
{
   InitializeComponent();

   button1.Click += new EventHandler(button_Click);
   button2.Click += new EventHandler(button_Click);
}

void button_Click(object sender, EventArgs e)
{
   label1.Text = "Hi ";
}

Now on both button clicks - the text of a label is printed as 'Hi' as the event is common between both buttons.

Now what I want is to pass some extra information to the on click event from both buttons , you can pass on any number and type of  objects as you want. for the example I will send a string and Enum to click events.

I will also need to modify the button click event , as I am going to send some parameters to event so I need to catch those in the event.

public Form1()
{
  InitializeComponent();

  button1.Click += delegate(object sender, EventArgs e) { button_Click(sender, e, "This is   From Button1", MessageType.B1); };

  button2.Click += delegate(object sender, EventArgs e) { button_Click(sender, e, "This is From Button2", MessageType.B2); };

}

void button_Click(object sender, EventArgs e, string message, MessageType type)
{
   if (type.Equals(MessageType.B1))
   {
      label1.Text = message;
   }
   else if (type.Equals(MessageType.B2))
   {
      label1.Text = message;
   }
}

enum MessageType
{
   B1,
   B2
}


No comments:

Post a Comment