Buttons in Flowlayoutpanel

1.2k views Asked by At

i add a button for each data row in a flowlayoutpanel with like

foreach (var Item in query.OrderBy(x=> x.menu_sort))
            {
                var btn = new Button
                {
                    Name = Item.menu_name,
                    Text = Item.menu_description,
                    Tag = Item.menu_name,
                    Size = new Size(107, 50),
                    Font = new Font("B Nazanin",10)
                };

                MainPanel.Controls.Add(btn);

-----> i want to click on buttons and open a form. <-----

2

There are 2 answers

0
Alicia On

I think you want to add an event handler at runtime to a control, right? You can do it this way:

btn.Click += new EventHandler(button_Click);

Then, you have to implement the method button_Click somewhere, with the correct signature:

private void button_Click(object sender, System.EventArgs e)
{
   // Do stuff
   MyForm form = new MyForm();
   form.Show();
}
0
Idle_Mind On

I want to click on buttons and open a form.

Wire up the Click() event for those buttons when you create them:

    private void Foo()
    {
        foreach (var Item in query.OrderBy(x=> x.menu_sort))
        {
            var btn = new Button
            {
                Name = Item.menu_name,
                Text = Item.menu_description,
                Tag = Item.menu_name,
                Size = new Size(107, 50),
                Font = new Font("B Nazanin",10)
            };

            btn.Click += Btn_Click;

            MainPanel.Controls.Add(btn);
        }
    }

    private void Btn_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        // now do something with "btn", maybe based on btn.Tag?
    }