[RESOLVED]Convert sender object to a control?
I'm creating checkboxes dynamically and adding them to a form.
Then I use a delegate to add events to the checkbox. (I have a function to handle the .click event of the checkboxes)
But, I can't tell which check box was clicked. How can I tell which one is clicked. I thought I could use the 'sender' object but it isn't working. :(
Here's my code:
Code:
// The delegate
public delegate void MyEventHandler(EventArgs e);
// Adding controls to the form and adding a handler for the .click event
private void Form1_Load(object sender, EventArgs e)
{
CheckBox c = new CheckBox();
c.Text = "yadda";
c.Tag = "ONE";
c.Location = new Point(20, 20);
this.Controls.Add(c);
c.Click += new System.EventHandler(MyDelegateFunction);
c = new CheckBox();
c.Text = "yadda";
c.Tag = "TWO";
c.Location = new Point(40, 40);
this.Controls.Add(c);
c.Click += new System.EventHandler(MyDelegateFunction);
}
// The function to handle all checkboxes .click event
public void MyDelegateFunction(Object sender, EventArgs e)
{
MessageBox.Show("raised..." + sender.ToString() + " " + e.ToString());
MessageBox.Show(sender.GetType().ToString());
}
In the MyDelegateFunction(), I need to know which checkbox sent the .click message to handle. How can I know which checkbox was clicked? :cry:
Thanks.
Re: Convert sender object to a control?
Personally, if I know that the sender is of type CheckBox then I would type cast the sender as a checkbox and check the name proprty to see which one it is. IE. ((CheckBox)sender).Name.
Re: Convert sender object to a control?
Since you haven't set the name of your controls, you could use Tag to identify your sender.
Code:
((CheckBox)sender).Tag.ToString()
Re: Convert sender object to a control?
Thanks guys.
I was trying to convert the sender to an object when I was trying to cast it. :blush:
Re: [RESOLVED]Convert sender object to a control?
Another way would be:
c# Code:
CheckBox cbx = sender as CheckBox;
if (cbx != null)
{
// Use cbx here.
}
The 'as' operator will attempt to cast the reference as the specified type and return null if it fails, where an explicit cast will throw an exception if it fails. It's better if there can be any doubt about the type of the object being cast. It is a good way to create more robust code.