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

我的任务是如果用户在文本框中输入 3。应该动态创建3个按钮并添加到面板中怎么做??????我正在使用按钮阵列请建议我

4

3 回答 3

0

例如,您可以使用它。

    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);
        }
    }
于 2013-10-18T11:12:37.857 回答
0

这篇文章中已经回答了一个类似的问题:

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

最好测试验证器始终是一个数字

   string a = textBox1.Text;
于 2013-10-18T11:26:06.703 回答
0

可能使用列表更合适?

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)
    }
}
于 2013-10-18T11:36:53.423 回答