当我点击button1
时,我正在尝试在表单上创建4个按钮,但按钮不会显示。为什么不呢?
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);
}
}
答案 0 :(得分: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]);
}
}
答案 1 :(得分:1)
您所做的只是创建一个按钮数组,并在索引处指定按钮。你的表单对这些按钮一无所知,它们可以是一个整数数组,也可以是所有重要事项。您需要将它们放在表单的容器中:
Controls.Add(b[i]);
现在,您的表单将取得它们的所有权,在处理容器时管理处理。
答案 2 :(得分: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);
}
}
}
答案 3 :(得分:0)
在表单上创建Panel
。并在您的代码中添加此行
panel1.Controls.Add(b[i])