无法使用 Controls.Add 获取实例



我正在以编程方式创建按钮。我不想使用 Button btn = new Button((;..btn.height=....控制。Add(btn(;.我使用的代码可以将按钮添加到窗体中,但我无法获取实例,因此无法创建 button.click 事件。谁能帮我解决它。我在下面使用的代码谢谢。

int k = 0;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
Controls.Add( 
new Button() 
{ 
Top = 50 + (50 * i), 
Left = 50 + (50 * j), 
Width = 50, Height = 50, 
Text = (++k).ToString()
});
}
}

如果您不想创建按钮,并直接订阅事件(我不知道为什么这很重要(,您可以这样做:

private void Method()
{
int k = 0;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
Controls.Add(new Button() { Top = 50 + (50 * i), Left = 50 + (50 * j), Width = 50, Height = 50, Text = (++k).ToString() });
}
}
Controls.OfType<Button>().ToList().ForEach(x => x.Click += Button_Click);
}
private void Button_Click(object sender, System.EventArgs e)
{
MessageBox.Show((sender as Button).Text);
}

最新更新