【问题标题】:How can I retrieve the input values of dynamically created textfields?如何检索动态创建的文本字段的输入值?
【发布时间】:2018-05-20 21:09:24
【问题描述】:

到目前为止,这是我的代码,其中我有一个名为 numericUpDown 的 numericupdown 项目和按钮。一旦用户在按下按钮时选择了一个数字,它就会动态创建字段。

private void createPerson_Click(object sender, EventArgs e)
{    
    Label[] person_Name = new Label[(int)this.numericUpDown.Value];
    TextBox[] person_txtinput = new TextBox[(int)this.numericUpDown.Value];

    for (int i = 0; i < this.numericUpDown.Value; i++)
    {    
        //create person name label 
        Person_Name[i] = new Label();
        Person_Name[i].Location = new System.Drawing.Point(20, 114 + i * 25);
        Person_Name[i].Size = new System.Drawing.Size(120, 15);
        Person_Name[i].Text = (i + 1).ToString() + @")" + "Person Name:";
        this.Controls.Add(Person_Name[i]);

        //create person name textbox
        PersonNameTxtInput[i] = new TextBox();
        PersonNameTxtInput[i].Location = new System.Drawing.Point(140, 114 + i * 25);
        PersonNameTxtInput[i].Size = new System.Drawing.Size(125, 20);
        this.Controls.Add(PersonNameTxtInput[i]);    
    }    
}



 private void save_Click(object sender, EventArgs e)
{
    for (int i = 0; j < this.numericUpDown.Value; i++)
    {
        MessageBox.Show("" + PersonNameTxtInput[i].Text);
    }
}

我的问题是,如何根据用户在按下保存按钮时创建的字段数量从文本框中获取所有值?

我已经尝试在保存按钮侦听器中使用代码,但是如何将 Label[] person_Name = new Label[(int)this.numericUpDown.Value]; 设为全局变量,以便我可以在保存按钮中访问它以进行循环。

【问题讨论】:

  • 有什么理由不能只遍历 this.Controls 吗?
  • 你能扩展你的问题吗,我对编码很陌生。如果我遍历 this.Controls 我也不会得到标签名称。我只需要文本字段中的值而不是标签。这是我写的一些代码。

标签: c# arrays winforms dynamic textbox


【解决方案1】:

好吧,我不知道你为什么要以这种特殊的方式这样做,我必须承认它似乎不是很有效,但你可以按照 Ryan_L 的建议进行并遍历 this.Controls 这样的控件

for(int i = 0; i < this.Controls.Count; i++)
{
    if(this.Controls[i] is TextBox) //skip buttons and labels
    {
        MessageBox.Show("" + this.Controls[i].Text);
    }
}

现在,关于您的问题如何定义一个全局变量以便您可以在循环的保存按钮中访问它...只需在 createPerson_Click之外定义两个数组> 像这样的事件:

Label[] person_Name;
TextBox[] person_txtinput;

private void button1_Click(object sender, EventArgs e)
{
    person_Name = new Label[(int)this.numericUpDown.Value];
    person_txtinput = new TextBox[(int)this.numericUpDown.Value];
    //the rest of the code
}

希望这会有所帮助。但是,您可能需要重新考虑整个方法。

【讨论】:

  • 嘿,我已经尝试过你的方法并且它有效,但是有没有办法到特定的文本字段组。例如,如果用户从 numericupdown 字段中选择 2 从而创建字段 person name , person surname 两次,我将如何将每个值存储在变量中。这样做的目的是我需要从用户那里获取输入并保存到一个 xml 文件中。
  • 我不确定我是否正确理解了这个问题,但如果我确实理解了,您可以将每个值存储到字符串列表中。因此,您可以使用类似下面的内容而不是 MessageBox.Show:myList.Add(this.Controls[i].Text); 然后,在 for 循环之后,您可以序列化列表。请参阅this 线程以了解如何序列化列表。
  • 我设法用我的方法做到了,似乎我为要保存在 ;s 中的数据指定了错误的位置。感谢您的帮助
猜你喜欢
  • 2013-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-21
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多