简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM