我想知道是否有人可以帮助我改进我的代码(?)
三个星期前,我决定学习C#/ C++(决定从c#开始)并且我正在尽我所能,但我在理解一些基础知识方面遇到了问题 - 例如数组.
我想添加"x"文本框(其中"x"是numericUpDown的值),点击按钮.
我找到了一个解决方法如何做到这一点,但我有这种感觉,可以用不同的(更好的)方式编写它(我假设高级程序员会使用列表或数组).
如果我错了,请原谅我,正如我之前提到的那样 - 我是新人并尽我所能去学习.
这是我的代码:
private void button1_Click(object sender, EventArgs e)
{
if (numericUpDown1.Value == 1)
{
txtbx1.AutoSize = true;
Controls.Add(txtbx1);
txtbx1.Location = new Point(70, 100);
}
else if (numericUpDown1.Value == 2)
{
txtbx1.AutoSize = true;
Controls.Add(txtbx1);
txtbx1.Location = new Point(70, 100);
txtbx2.AutoSize = true;
Controls.Add(txtbx2);
txtbx2.Location = new Point(70, 130);
}
else if (numericUpDown1.Value == 3)
{
txtbx1.AutoSize = true;
Controls.Add(txtbx1);
txtbx1.Location = new Point(70, 100);
txtbx2.AutoSize = true;
Controls.Add(txtbx2);
txtbx2.Location = new Point(70, 130);
txtx3.AutoSize = true;
Controls.Add(txtbx3);
txtbx3.Location = new Point(70, 160);
}
}
Run Code Online (Sandbox Code Playgroud)
不要重复自己,以一种简单的方式,你可以这样做:
private void button1_Click(object sender, EventArgs e)
{
int y = 100;
int x = 70;
for (int i = 0; i < numericUpDown1.Value; i++)
{
var txtbx = new TextBox();
txtbx.AutoSize = true;
Controls.Add(txtbx);
txtbx.Location = new Point(x, y);
// Increase the y-position for next textbox.
y += 30;
}
}
Run Code Online (Sandbox Code Playgroud)
TextBox您可以随时创建控件,而不是预先创建控件:
// This is optional - in case you want to save these for use later.
List<TextBox> newTextBoxes = new List<TextBox>();
private void button1_Click(object sender, EventArgs e)
{
int y = 100;
for (int i=0;i<numericUpDown1.Value;++i)
{
TextBox newBox = new TextBox
{
AutoSize = true,
Location = new Point(70, y)
};
y += 30;
Controls.Add(newBox);
// This saves these for later, if required
newTextBoxes.Add(newBox);
}
}
Run Code Online (Sandbox Code Playgroud)