Reputation: 371
I'd like to distinguish each of the Event handler.
(I have only one in my code below. I mean dynamic handler will be the best but, any kind of workarounds will be fine too.)
Please help me.
Thanks !
List<Button> VuttonList = new List<Button>();
private void Form1_Load(object sender, EventArgs e)
{
Button Vutton;
int Kount = 10;
for (int i = 0; i < Kount ; i++)
{
Vutton = new Button();
Vutton.Text = ( i + 1 ).ToString() ;
Vutton.Location = new Point(10, 24 * ( i + 1 ) );
Controls.Add( Vutton );
Vutton.Click += new EventHandler(Kommon);
VuttonList.Add( Vutton );
}
}
private void Kommon(object sender, EventArgs e)
{
MessageBox.Show( sender.ToString() );
}
Upvotes: 1
Views: 1142
Reputation: 125197
One event handler is enough, you can cast the sender to Button
and this way you know which button has been clicked. Also you can set Name
property of buttons when you create them or assign Tag
property of them and use it later.
for (int i = 0; i < Kount ; i++)
{
Vutton = new Button();
//...set properties
//Also add Name:
Vutton.Name = string.Format("Vutton{0}", i);
//Also you can add Tag
Vutton.Tag = i;
Controls.Add( Vutton );
Vutton.Click += new EventHandler(Kommon);
//... other stuff
}
Then you can use properties of button this way:
private void Kommon(object sender, EventArgs e)
{
var button = sender as Button;
//You can use button.Name or (int)button.Tag and ...
MessageBox.Show(button.Name);
}
Also to layout your buttons, you can use a FlowLayoutPanel
or a TableLayoutPanel
.
Upvotes: 1