1

i am working on a project where a new button is created x times (for the sake of this question: x is defined by a user input at the moment. In the final version this will be handled by the amount of entries in an SQL-Databank). These buttons then go into a ScrollViewer. I need every single dynamically created button to have a unique event on click. So if button 1 is clicked, event 1 is being executed and so on... This of course means that if for instance 5 buttons are created, every single one of them needs to trigger their own function. The names of the functions could be named BtnClick + i. So what would be a viable solution to that? Could not get the EventHandler to work the way i need it to.

Here is the code:

    private void TextEnter(object sender, KeyEventArgs e)
    {
        if (Keyboard.IsKeyDown(Key.Enter))
        {
            TextBox testBox = (TextBox)sender;
            int entry = Int32.Parse(testBox.Text);
            Console.WriteLine(entry);

            for (int i = 1; i < entry + 1; i++)
            {
                Button testBtn = new Button();
                testBtn.Content = i;
                testBtn.FontSize = 20;
                testBtn.Foreground = new SolidColorBrush(Colors.White);
                testBtn.Width = ListPanel.ActualWidth;
                testBtn.Height = 60;
                testBtn.FontWeight = FontWeights.Bold;
                testBtn.Background = new SolidColorBrush(Colors.Transparent);
                testBtn.Click += new EventHandler();
                ListPanel.Children.Add(testBtn);
            }
señor.woofers
  • 119
  • 2
  • 8
  • Look here [enter link description here](https://stackoverflow.com/questions/45779/c-sharp-dynamic-event-subscription) and here [enter link description here](https://stackoverflow.com/questions/8694235/attach-event-to-dynamic-object) – Volodymyr Zakolodyazhny May 19 '21 at 18:51

1 Answers1

2

You could use the same event handler and switch on the Button's Content:

private void TextEnter(object sender, KeyEventArgs e)
{
    if (Keyboard.IsKeyDown(Key.Enter))
    {
        ...
        for (int i = 1; i < entry + 1; i++)
        {
            Button testBtn = new Button();
            testBtn.Content = i;
            testBtn.FontSize = 20;
            testBtn.Foreground = new SolidColorBrush(Colors.White);
            testBtn.Width = ListPanel.ActualWidth;
            testBtn.Height = 60;
            testBtn.FontWeight = FontWeights.Bold;
            testBtn.Background = new SolidColorBrush(Colors.Transparent);
            testBtn.Click += TestBtn_Click;
            ListPanel.Children.Add(testBtn);
        }
    }
}

private void TestBtn_Click(object sender, RoutedEventArgs e)
{
    Button button = (Button)sender;
    int content = Convert.ToInt32(button.Content);
    switch (content)
    {
        case 1:
            //do something for the first button
            break;
        case 2:
            //do something for the second button...
            break;
    }
}

Or create the event handler using an anonymous inline function:

testBtn.Click += (ss,ee) => { ShowPage(i); };
mm8
  • 163,881
  • 10
  • 57
  • 88
  • Yeah seems good. But in theory 1000 buttons could be created. Hardcoding all the cases is not something i look forward to. Is there any way of creating a new case for the amount of buttons? – señor.woofers May 19 '21 at 19:26
  • So instead of using a `switch` statement in a single method you want to create 1000 different methods...? Hmm. Why do you even need to handle each button click differently? – mm8 May 19 '21 at 19:27
  • What's the difference between clicking on button 1 and button 900 for example? – mm8 May 19 '21 at 19:29
  • Each button in the end will show a different page containing different sets of data. In the end, the user can add a new entry containing a name, date and so on. This data will then be saved to an sql server. When the program is started, it checks how many of these entries are in the databank and create an adequate amount of buttons - one for each. When clicking the button, a page is revealed that shows the data of that entry saved in the databank. – señor.woofers May 19 '21 at 19:33
  • Use an anonymous inline function then? See my edit? – mm8 May 19 '21 at 19:35
  • I've never used inline functions. What exactly does the (ss,ee) do? I guess the "ShowPage(i); part can be swapped out for anything? – señor.woofers May 19 '21 at 19:39
  • Yes, that's the implementation of the [anonymous function](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/anonymous-functions?WT.mc_id=DOP-MVP-5001077). – mm8 May 19 '21 at 19:40
  • Great! That helped a lot. Any idea how to then define which button does what? i of course will always be the number of entries there is as a whole. Still need to identify which button is pressed an then for instance just print out "Button1 pressed" – señor.woofers May 19 '21 at 19:45
  • I already showed you how to do this. Cast the `Content` property of the `sender` argument. – mm8 May 19 '21 at 19:47
  • Oh yeah sorry. Works! Thanks a lot – señor.woofers May 19 '21 at 19:49