señor.woofers
señor.woofers

Reputation: 129

WPF C# create Click event for dynamically created button

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);
            }

Upvotes: 1

Views: 2273

Answers (1)

mm8
mm8

Reputation: 169390

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); };

Upvotes: 2

Related Questions