Mahan
Mahan

Reputation: 11

how to add a click handler to dynamic created button in c# wpf (an object is not created)

by using the code below(code1) i created a dynamic stack panel to add buttons by an option file generated from before to my program but i wonder how to add click listener to each button generated since i cant create an object from each button.

i tried adding click listener by using the mentioned code (code2) but it was not a success and also i tend to go throw the controls and find each button but i got null refrence exception (code 3)

//code1
StackPanel option_row = new StackPanel();
option_row.Name = "option_row" + i.ToString();
option_row.Children.Add(
               new Button
               {
                   Name = "write_btn" + i.ToString(),
                   VerticalAlignment = VerticalAlignment.Top,
                   Margin = new Thickness(5),
                   Content = "Write",
                   Height = 55,
                   Width = 80
               }
               );
//code2
                option_row.Children.Add(
               new Button
               {
                   Name = "write_btn" + i.ToString(),
                   VerticalAlignment = VerticalAlignment.Top,
                   Margin = new Thickness(5),
                   Content = "Write",
                   Height = 55,
                   Width = 80
               }.Click += new RoutedEventHandler(home_read_click)
               );

private void home_read_click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
        }
//code3
private void btn_sorter()
        {
            for (int i = 0; i < options_num; i++)
            {
                StackPanel x =(StackPanel) FindName("option_row" + i.ToString());
                foreach (Button item in x.Children)
                {
                    if (item.Name.Contains("read"))
                    {
                        home_read_buttons[i] = item.Name;
                    }
                    else if (item.Name.Contains("write"))
                    {
                        home_write_buttons[i] = item.Name;
                    }

                }
       }

        }

erors in code 2: The best overloaded method match for

System.Windows.Controls.UIElementCollection.Add(System.Windows.UIElement)' has some invalid arguments
Argument 1: cannot convert from 'void' to 'System.Windows.UIElement'

Upvotes: 1

Views: 917

Answers (1)

Meysam
Meysam

Reputation: 580

you should create Button object at first, then assign it to 'option_row.Children' like this:

var btn = new Button
           {
               Name = "write_btn" + i.ToString(),
               VerticalAlignment = VerticalAlignment.Top,
               Margin = new Thickness(5),
               Content = "Write",
               Height = 55,
               Width = 80
           };
 btn.Click += new RoutedEventHandler(home_read_click);
 option_row.Children.Add(btn);

Upvotes: 1

Related Questions