OK, I am sticking with my original sample, but I have changed it to use an
array of buttons. I am using one event handler for all buttons, but the
event handler determines wich button fired the event and takes action
accordingly. Make sure to declare the array of buttons as private date
member of the form:
private Button[] btn;
Then declare the array of buttons (including the size of the array) during
runtime, in the example in the form Load event:
private void Form1_Load(object sender, System.EventArgs e)
{
btn = new Button[4];
for (int i = 0; i < 4; i++)
{
btn = new Button();
btn.Text = "New Button " + i.ToString() ;
btn.Location = new System.Drawing.Point(10,i * 30);
btn.Size = new System.Drawing.Size(100, 20);
this.Controls.Add(btn);
btn.Click += new EventHandler(btn_Click);
}
}
Then determine in the event handler which button fired the event and take
the correct action.
private void btn_Click(object sender, System.EventArgs e)
{
if ((sender as Button) == btn[0] )
{
MessageBox.Show("btn[0] clicked");
}
else if ((sender as Button) == btn[1])
{
MessageBox.Show("btn[1] clicked");
}
else
{
MessageBox.Show("another button clicked");
}
}
I guess something similar should be possible for listboxes.
Regards,