我正在制作一个程序,它将通过 for 循环在屏幕上制作按钮。这很重要,因为用户需要访问按钮的数量,并且可能会随着每次运行而改变。这是我到目前为止的代码:
public Form1()
{
InitializeComponent();
int top = 5;
int left = 5;
for (int i = 0; i < 10; i++)
{
Button button = new Button();
button.Height = 50;
button.Left = left;
button.Top = top;
this.Controls.Add(button);
left += button.Width + 2;
}
}
我想要的基本上是这样的:
Button b+i = new Button();
就像组合两个字符串时,我希望循环中第一次运行时按钮的名称是 b0,然后是 b1,然后是 b2,依此类推。
我使用 Visual Studio,InitializeComponent() 转到编辑器生成的代码来制作窗口和东西。除了 window ,什么都没有。
感谢您的帮助!
最佳答案
担心变量名是解决此问题的错误方法。有几种选择:
使用列表
List<Button> buttons;
public Form1()
{
InitializeComponent();
buttons = new List<Button>();
int top = 5;
int left = 5;
for (int i = 0; i < 10; i++)
{
Button button = new Button();
button.Height = 50;
button.Left = left;
button.Top = top;
this.Controls.Add(button);
buttons.Add(button);
left += button.Width + 2;
}
}
//now instead of 'b1', it's 'buttons[1]'
您也可以使用 OfType() 方法创建:
var buttons = this.Controls.OfType<Button>().ToList();
这些可以结合 FlowLayoutPanel 或 TableLayoutPanel 来简化代码:
public Form1()
{
InitializeComponent();
for (int i = 0; i < 10; i++)
{
Button button = new Button();
button.Height = 50;
FlowLayoutPanel1.Controls.Add(button); //panel handles Left/Top location
}
}
该面板还具有帮助您的应用在不同 dpi 或屏幕/窗口尺寸下缩放的优势。
其中任何一个也可以被改编为开始考虑连接到数据源(并减少代码):
var buttons = Enumerable.Range(0, 10).Select(b => new Button {
Height = 50,
Left = 5 + ( b * (BUTTONWIDTH + 2) ),
Top = 5,
Name = String.Format("Button{0}", b)
});
//buttons.ToList()
//or
//this.Controls.AddRange(buttons.ToArray())
//or
//FlowLayoutPanel1.Controls.AddRange(buttons.ToArray()) //Remove Left/Top code
但是,在您可以让按钮真正做某事之前,所有这些都是毫无意义的。您需要(至少)Click 事件的事件处理程序:
foreach (var b in butons)
{
b.Click += (s,e) =>
{
//click code for all of the buttons goes here
// you can tell the buttons apart by looking at the "s" variable
};
}
关于c#在for循环中更改控件的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34668019/