Search code examples
c#.netwpfbuttonbuttonclick

How to know which button is clicked in wpf button created programatically using c#


I am under a situation where i have to click the button which are created dynamically with programming in c# (because user decides at run time how many button to be created). I do so by writing code like this:

int runTimeIntegerValue = 6; //Lets say its 6
Button[] childGridSavebutn = new Button[runTimeIntegerValue -1];
for (int j = 0; j < runTimeIntegerValue; j++)
{   
    childGridSavebutn[j] = GenerateButton("Save Table");
    childSmallgrid[j] = generateRowColumnGrid(1, 1);
    Grid.SetColumn(childGridSavebutn[j], 1);
    Grid.SetRow(childGridSavebutn[j], i);
    childSmallgrid[j].Children.Add(childGridSavebutn[j]);

    childGridSavebutn[j].Click += (source, e) =>
    {
        txtBoxOrder[j].Text = "I am from " + j;
        MessageBox.Show("I am from " + j);  //This message always show "I am From 5"
    };

}
private Button GenerateButton(string p)
{
    Button btn = new Button();
    //btn.Name = p;
    btn.Content = p;
    btn.Width = 80;
    btn.HorizontalAlignment = HorizontalAlignment.Center;
    btn.Height = 20;           
    return btn;
}

After I popup a message MessageBox.Show("I am from " + i); to know the message box is popuped from which button . It always popups 5 (as last count of i is 5).

So How to know which button is clicked, by click on that button? As there are 5 buttons, so i should know by click on the button that button number 1/2/3/4/5 is clocked by pop up of message with respected i position. (I mean button at ith position is clicked, and message must show this the "I am from 2" when 2nd button is clicked)

SUMMARY: I have childGridSavebutn[1 to 5] array (it could be even 10 decided run time by user). And it display 5 buttons, How to know which button is clicked ? (as it always popups 5th one) because further i have to generate button click events receptively. How will i do that if i do not know which button is clicked. At last UI has to repeat like this 5 times


Solution

  • Replace

    childGridSavebutn[i].Click += (source, e) =>
    {    
        txtBoxOrder[i].Text = "I am from " + i;
        MessageBox.Show("I am from " + i);  //This message always show "I am From 5"
    };
    

    with

    childGridSavebutn[i].Tag = i;
    childGridSavebutn[i].Click += (source, e) =>
    {
        var button = source as Button;
        var index = (int)button.Tag;
        txtBoxOrder[index].Text = "I am from " + index;
        MessageBox.Show("I am from " + index);
    };
    

    You must need to set the the value of i while subscribing the event, you can use Tag property for this. Otherwise you will get the last updated value of i on every message.