Martin Gabriel
Martin Gabriel

Reputation: 59

Event on non existing button

I'm working on WPF app and I want to dynamiclly add buttons. For example I have a loop, which add 5 new buttons.

int i;

for (i = 0; i < 5; i++)
{
    Button addButton = new Button();
    addButton.Name = "addButton" + i;
    addButton.Content = "addButton" + i;
    this.devicesButtonStackPanel.Children.Add(addButton);
}

Now I have 5 buttons in StackPanel.

I need event on every button.

I'm trying to use this:

private void addButton0_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    MessageBox.Show("test");
}

But it doesn't work.

Upvotes: 0

Views: 101

Answers (4)

Niranjan Singh
Niranjan Singh

Reputation: 18270

You have not attach your event handler to the MouseDoubleClick event. Please attach your control event to event handler method as you are showing as:

addButton.MouseDoubleClick += addButton0_MouseDoubleClick;

Your code should be like as like the below code snippet:

int i;

for (i = 0; i < 5; i++)
{
    Button addButton = new Button();
    addButton.Name = "addButton" + i;
    addButton.Content = "addButton" + i;
  //Use the addition assignment operator (+=) to attach your event handler to the event.
    addButton.MouseDoubleClick += addButton0_MouseDoubleClick;
    this.devicesButtonStackPanel.Children.Add(addButton);
}

you can do work with these button as below:

  private void addButton0_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
       string buttonName = ((Button)sender).Name;
       string buttonNumber = buttonName.SubString(0,buttonName.Length -1 );

       switch(buttonNumber)
       {
         case "0":
         // do work for 0
          break;
          case "1":
          // do work for 1
         break;
        } 
    }

Refer: How to: Subscribe to and Unsubscribe from Events (C# Programming Guide)

Upvotes: 1

CodingIntrigue
CodingIntrigue

Reputation: 78595

You need to bind to the event when you create the button:

Button addButton = new Button();
addButton.Name = "addButton" + i;
addButton.Content = "addButton" + i;
// Bind your handler to the MouseDoubleClick event
addButton.MouseDoubleClick += addButton0_MouseDoubleClick;
this.devicesButtonStackPanel.Children.Add(addButton);

Upvotes: 5

Daniel
Daniel

Reputation: 9521

You simply do it in your code

                Button addbutton = new Button();
                addbutton.Click += addButton0_MouseDoubleClick;

Upvotes: 3

Ivan Crojach Karačić
Ivan Crojach Karačić

Reputation: 1911

Just subscribe each button the the handler

addButton.Clicked += addButton0_MouseDoubleClick;

Upvotes: 2

Related Questions