Passing Parameters to Events - 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.

  1. public Form1()  
  2. {  
  3.    InitializeComponent();  
  4.   
  5.    button1.Click += new EventHandler(button_Click);  
  6.    button2.Click += new EventHandler(button_Click);  
  7. }  
  8.   
  9. void button_Click(object sender, EventArgs e)  
  10. {  
  11.    label1.Text = "Hi ";  
  12. }  
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 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.
  1. public Form1()  
  2. {  
  3.   InitializeComponent();  
  4.   
  5.   button1.Click += delegate(object sender, EventArgs e) { button_Click(sender, e, "This is   From Button1", MessageType.B1); };  
  6.   
  7.   button2.Click += delegate(object sender, EventArgs e) { button_Click(sender, e, "This is From Button2", MessageType.B2); };  
  8.   
  9. }  
  10.   
  11. void button_Click(object sender, EventArgs e, string message, MessageType type)  
  12. {  
  13.    if (type.Equals(MessageType.B1))  
  14.    {  
  15.       label1.Text = message;  
  16.    }  
  17.    else if (type.Equals(MessageType.B2))  
  18.    {  
  19.       label1.Text = message;  
  20.    }  
  21. }  
  22.   
  23. enum MessageType  
  24. {  
  25.    B1,  
  26.    B2  
  27. }  

Ebook Download
View all
Learn
View all