Adrian Marinica
Adrian Marinica

Reputation: 2201

Access control properties from its dynamically created Event Handler

I am developing a C# WinForms application. On the FormLoad event, I dynamically create and add to the form 100 buttons without text, but with names like button1, button2 etc. Also, onto these buttons, after their creation, I dynamically link a unique event handler for the ButtonClick event. How can I access the button's properties from within the event handler (more specifically the button name)? If I use this.Name, I get the name of the form, and not the name of the button.

Later Edit: (for those who might wonder here in search of solutions)

private void function1()
{
    Button a = new Button();

    a.Name = "button" + (i * j).ToString();
    a.Click += new EventHandler(OnFieldButtonClicked);
}

private void OnFieldButtonClicked(object sender, EventArgs e)
{
    Button button = (Button)sender;
    MessageBox.Show(button.Name);
}

Upvotes: 2

Views: 1898

Answers (1)

Akram Shahda
Akram Shahda

Reputation: 14781

The sender argument is the event handler encapsulates an instance of the object that has triggered the event:

Button button = (Button) sender;
String text = button.Text;

Upvotes: 7

Related Questions