dynamically adding buttons and button objects in panel

private void button1_Click(object sender, EventArgs e)
{
    string a = textBox1.Text;
    int h = Convert.ToInt32(a);

    for (int i = 0; i <= h; i++)
    {
       buttonArray[i] = new Button();
       buttonArray[i].Size = new Size(60, 23);
       buttonArray[i].Location = new Point(40,20);
        panel1.Controls.Add(buttonArray[i]);
    }
}

my task is if user enter 3 in text box. 3 buttons should be created dynamically and added to panel how to do that?????? i am using button array please suggest me


ANSWERS:


For example you can use this.

    private void button1_Click(object sender, EventArgs e)
    {
        panel1.Controls.Clear();
        string a = textBox1.Text;
        int h = Convert.ToInt32(a);

        for (int i = 0; i <= h; i++)
        { 
            var btn = new Button {Size = new Size(60, 23), Dock=DockStyle.Left, Text=h.ToString() };
            btn.Click+= delegate(object sender, EventArgs e)  { //your commands }; 
            panel1.Controls.Add(btn);
        }
    }

In this post already answered a similar question:

private void button1_Click(object sender, EventArgs e)
    {
        string a = textBox1.Text;
        int h = Convert.ToInt32(a);

        for (int i = 0; i <= h; i++)
        {
            var b = new Button { Size = new Size(60, 23), Location = new Point(4 + i * 57, 20), Text = string.Format("button{0}", i) };
            b.Click += b_Click;
            panel1.Controls.Add(b);
        }
    }

    void b_Click(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }

it is desirable to test the validator to always have been a number

   string a = textBox1.Text;

May be using a List is more situable?

List<Button>Buttons=new List<Buttons>();

private void button1_Click(object sender, EventArgs e)
{
   Buttons.Clear();
   string a = textBox1.Text;
   //here should be checking if "a" is digit and is not empty
    int h = Convert.ToInt32(a);

    for (int i = 0; i <= h; i++)
    {
      Button btn=new Button();
      btn.Parent=panel1;
      btn.Size=new Size(60, 23);
      btn.Location = new Point(40,5+25*i); //arrange verically
      btn.Text = "Button "+i.ToString();
      btn.Click+=btn_Click;   
      btn.Tag="Some Value you want to restore after button click";

      Buttons.Add(btn)
    }
}


 MORE:


 ? Populate Buttons With Database Values c#
 ? Adding GUI controls dynamically
 ? trying to add/remove controls to a form
 ? removing dynamically created controls C#
 ? Add columns to a datatable in c#?
 ? ASP NET - C#: Access controls by Id
 ? Add a bunch of controls dynamically to screen in iOS
 ? Can't dynamically add new literal to ASP.NET Panel Control
 ? Add dynamic ASP.NET controls via a DropDownList to the page
 ? WinForm: control won't add to a panel