我对使用 numericUpDown 添加控件的代码有疑问(例如,如果 numericUpDown 值等于 3,则用户接收 3 个文本框)。
感谢 stackoverflow 用户,我改进了我的代码。
在改进之前它看起来像这样:
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);
}
}
改进后:
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;
}
}
现在的问题是我不知道如何为生成的文本框分配名称。(在改进之前,我可以将它们命名为 - txtbx1、txtbx2、txtbx3...)
需要改进的代码:
private void button3_Click(object sender, EventArgs e)
{
    try
    {
        double a, b, c, sum;
        a = double.Parse(txtbx1.Text);
        b = double.Parse(txtbx2.Text);
        c = double.Parse(txtbx3.Text);
        sum = a + b + c;
        label1.Text = sum.ToString();
    }
    catch (Exception ex)
        {
            MessageBox.Show("error");
        }
请注意,我是初学者,通过观看 youtube 教程学习 c# ;) 我确实意识到我的问题可能很愚蠢,但我自己无法解决这个问题。
提前感谢您的时间和帮助。
