动态添加到表单的按钮不显示
本文关键字:按钮 显示 表单 添加 动态 | 更新日期: 2023-09-27 18:01:31
当我点击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);
}
}
您只创建了它们,但您还需要将它们添加到您的表单: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]);
}
}
您所要做的就是创建一个按钮数组,并在索引处分配按钮。表单对这些按钮一无所知,此时它们可以是整数数组或任何重要的东西。您需要将它们放入表单的容器中:
Controls.Add(b[i]);
现在您的表单将获得它们的所有权,并在容器被处置时管理处置。
试试这个:
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);
}
}
}
在表单上创建Panel
。并在你的代码
panel1.Controls.Add(b[i])