0

当我单击 时,我试图在我的表单上创建 4 个按钮button1,但这些按钮没有显示出来。为什么不?

private void button1_Click(object sender, EventArgs e)
{
   Button[] b = new Button[4];
   for (int i=0; i < 4; i++)
   {
      b[i] = new Button();
      b[i].Name = "button" + i;
      b[i].Location = new Point(43, 39 + 10 * i);
      b[i].Size = new Size(158, 48);
   }
}
4

4 回答 4

5

您只创建了它们,但您还需要将它们添加到您的表单中:this.Controls.Add(b[i]);

private void button1_Click(object sender, EventArgs e)
{
   Button[] b = new Button[4];
   for (int i=0; i < 4; i++)
   {
       b[i] = new Button();
       b[i].Name = "button" + i;
       b[i].Location = new Point(43, 39 + 10 * i);
       b[i].Size = new Size(158, 48);

       this.Controls.Add(b[i]);
   }
}
于 2013-02-28T16:56:13.323 回答
1

您所做的就是创建一个按钮数组,并在索引处分配按钮。您的表单对这些按钮一无所知,它们可能是整数数组或此时任何重要的东西。您需要将它们放入表单的容器中:

Controls.Add(b[i]);

现在您的表单将拥有它们的所有权,在容器被处置时管理处置。

于 2013-02-28T16:57:45.637 回答
1

试试这个:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace winFormButtons
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Button[] b = new Button[4];
            for (int i = 0; i < 4; i++)
            {
                b[i] = new Button();
                b[i].Name = "button" + i;
                b[i].Location = new Point(43, 39 + 10 * i);
                b[i].Size = new Size(158, 48);    
                b[i].Click += new EventHandler(OnClick);
                this.Controls.Add(b[i]);
            }
        }

        public void OnClick(object sender, EventArgs e)
        {    
            MessageBox.Show("Hello Handler:" + ((Button)sender).Name);    
        }
    }
}
于 2013-02-28T17:03:53.137 回答
0

Panel在您的表单上创建一个。并在您的代码中添加这一行

panel1.Controls.Add(b[i])
于 2013-02-28T16:59:38.853 回答