使用C#从动态创建的文本框和标签创建变量

时间:2018-03-23 02:53:32

标签: c# input dynamic

我想使用.Name分配的名称从文本框输入然后计算并输出到标签。

我不知道如何引用这些输入,因为它们目前有名称但没有指定的变量。

对不起,如果我没有多大意义,我不是一个非常熟练的编码员。

public partial class Form1 : Form
{
    List<TextBox> Txt1 = new List<TextBox>();
    public Form1()
    {
       InitializeComponent();

       for (int i = 0; i < 4; i++)
       {
            for(int j = 0; j < 7; j++)
            {
                if (j == 0)
                {
                    var txtbox = new TextBox();
                    txtbox.Location = new Point(163 + (i * 220), (36));
                    txtbox.Name = i + "Names";
                    txtbox.Text = txtbox.Name;
                    txtbox.Width = 40;
                    this.Controls.Add(txtbox);                       
                }
                else if (j>0 && j<6)
                {                      
                    var extratxt = new TextBox();
                    extratxt.Location = new Point(163 + (i * 220), (36+ 36 * j));
                    extratxt.Name = i + "Input" + j;
                    extratxt.Text = extratxt.Name;
                    extratxt.Width = 70;
                    this.Controls.Add(extratxt);

                    var percentbox = new Label();
                    percentbox.Location = new Point(163 + (90+ i * 220), (36 + 36 * j));
                    percentbox.Name = i + "Percent" + j;
                    percentbox.Text = percentbox.Name;
                    percentbox.Width = 50;
                    this.Controls.Add(percentbox);

                    var gradebox = new Label();
                    gradebox.Location = new Point(163 + (150 + i * 220), (36 + 36 * j));
                    gradebox.Name = i + "Grade" + j;
                    gradebox.Text = gradebox.Name;
                    gradebox.Width = 50;
                    this.Controls.Add(gradebox);
                }
                else
                {
                    var totals = new Label();
                    totals.Location = new Point(163 + (i * 220), (36 + 36 * j));
                    totals.Name = i + "Total";
                    totals.Text = totals.Name;
                    totals.Width = 40;
                    this.Controls.Add(totals);
                    ...
                }
                ...
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

希望我理解正确。
基本上,您的难点是如何通过名称访问存储在动态创建控件列表中的实例,对吗?

好吧,您可以使用.FirstOrDefault()选择具有特定属性的实例。例如,

private void Form1_Load(object sender, EventArgs e)
{
    List<TextBox> tbList = new List<TextBox>();
    for (int i = 0; i < 3; i++)
    {
        TextBox tb = new TextBox();
        tb.Text = "Test" + i.ToString();
        tb.Name = "TextBox" + (i + 1).ToString();
        tb.Location = new Point(0, 25 * i);
        tb.Tag = i;
        tbList.Add(tb);
        this.Controls.Add(tb);
    }
    var tb2 = tbList.FirstOrDefault(tb => tb.Name == "TextBox2");
    if (tb2 != null)
        tb2.Text = "Modified text";

    var sum = tbList.Sum(tb => (int)tb.Tag);
}