2

我想知道是否有人可以帮助我改进我的代码(?)

三周前,我决定学习 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);
    }
}
4

3 回答 3

6

不要重复自己,以一种简单的方式,您可以这样做:

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;
    }
}
于 2013-08-02T20:38:28.843 回答
5

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);
     }
}
于 2013-08-02T20:36:50.153 回答
0

你可以做两件事之一。第一种是使用switch语句,或者我更喜欢使用循环,尽管在使用 gui 时这可能会有点棘手。像这样的东西:

for (int i = 0; i < numericUpDown1.Value; i++)
    {
        //Make an TextBox Array or instantiate a new TextBox each iteration
            //and set properties here
    }

但正如我所说,如果您在循环中执行这些文本框的放置可能会有些棘手,因此仅使用switch语句会更容易。它们使用起来相对简单,但如果您遇到任何问题,请告诉我们。

此外,在您的代码中添加注释,为文本框和其他 GUI 元素提供有意义的名称;我知道设计师会自动为它们分配名称,现在这不是问题,但是在使用许多元素时会变得非常混乱。

于 2013-08-02T20:39:48.323 回答