我想知道如何做这样的事情:
我需要根据表示所需按钮数量的整数值创建一个具有特定数量按钮的Form,然后为它们指定自己的特定名称,以便每个按钮都有自己独特的事件处理程序。
我可以想到这样做的一个真实例子是Windows登录屏幕,其中创建的控件数量取决于用户数量以及是否有Guest帐户。你怎么认为他们编程了?
谢谢。
答案 0 :(得分:1)
for (int i = 0; i < 5; i++)
{
Button newButton = new Button();
newButton.Name = "button" + i.ToString();
newButton.Text = "Button #" + i.ToString();
newButton.Location = new Point(32, i * 32);
newButton.Click += new EventHandler(button1_Click);
this.Controls.Add(newButton);
}
private void button1_Click(object sender, EventArgs e)
{
if (((Button)sender).Name == "button0")
MessageBox.Show("Button 0");
else if (((Button)sender).Name == "button1")
MessageBox.Show("Button 1");
}
答案 1 :(得分:0)
不知何故,您必须定义所有按钮的名称。我建议你创建一个新的字符串数组并在里面写下按钮名,然后在按钮创建循环中使用它们:
//do the same length as the for loop below:
string[] buttonNames = { "button1", "button2", "button3", "button4", "button5" };
for (int i = 0; i < buttonNames.Lenght; i++)
{
Button newButton = new Button();
newButton.Name = "button" + i.ToString();
newButton.Text = buttonNames[i]; //each button will now get its own name from array
newButton.Location = new Point(32, i * 32);
newbutton.Size = new Size(25,100); //maybe you can set different sizes too (especially for X axes)
newButton.Click += new EventHandler(buttons_Click);
this.Controls.Add(newButton);
}
private void buttons_Click(object sender, EventArgs e)
{
Button btn = sender as Button
MessageBox.Show("You clicked button: " + btn.Text + ".");
}