tags:

views:

48

answers:

2

Hi

I am trying to create buttons at runtime. My Question is that How should I add an Event to each of the buttons at runtime mode also?

For example:

Button btn;
int i =0;
int j =0;
List<Button> listBTN = new List<Button>();

private void button1_Click(object sender, EventArgs e)
    {
        btn = new Button();
        btn.Location = new Point(60 + i, 90);
        btn.Size = new Size(50, 50);
        btn.Name = "BTN";

        listBTN.Add(btn);

        i = i + 50;

        foreach(Button b in listBTN){
        this.Controls.AddRange(new Button[] {b});
        }
    }

image

+3  A: 
btn.Click += yourMethod;

private void yourMethod(object sender, EventArgs e)
{
    // your implementation
    Button btn = sender as Button;
    if (btn != null)
    {
        //use btn
    }
}

if you want to add the event when you declare the button use:

btn.Click += delegate
{
     //your implementation
};
Nissim
that's just adding a same event to all of the buttons. What I'm trying to figure out is how to put a unique event to each of the buttons.
Rye
The event handler method which is reused. The event instance is created with each instance of the button.
aqwert
for that - give each button a unique name, and in the event handler use the btn.Name to know which is it, or use 'AnonymousMethods':btn.Click += new delegate{//your implementation here'};
Nissim
@NissimI think that's the solution. I'll try.
Rye
+1  A: 

You can do something like this:

Button btn = new Button();
btn.Name = "BTN" + i.ToString(); //just to be sure you can distinguish between them
btn.Click += new EventHandler(btn_Click);

And add default handler for all buttons:

    void btn_Click(object sender, RoutedEventArgs e)
    {
        Button btn = (Button)sender;
        MessageBox.Show("You have clicked button number " + btn.Name);
    }
veljkoz
Yes yes, I think you got my point. I also tried that solution a while ago. But What I want is that every time I add a button I'm also adding an event to that button. Is that possible?
Rye
Got it, this is also correct. Thank you
Rye