【问题标题】:How to fetch data from dynamically created textboxes (windows application)如何从动态创建的文本框(Windows 应用程序)中获取数据
【发布时间】:2014-06-01 07:12:14
【问题描述】:

我使用下面的代码通过最初给出文本框的总数来动态创建文本框。在我向这些文本框输入值后,我如何从中获取值。就像我将计数设为 3 一样,将创建 3 个文本框。现在,我在每个文本框中输入数据。我如何读取我输入到这些 texbox 中的值。

int a = 1;
    public Form1()
    {
        InitializeComponent();
    }

public System.Windows.Forms.TextBox AddNewTextBox()
{
        System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox();
        this.Controls.Add(txt);
        txt.Top = a * 25;
        txt.Left = 100;
        txt.Name = "txt" + this.a.ToString();
        txt.Text = "TextBox " + this.a.ToString();
        a = a + 1;
        return txt;
}



 private void button1_Click(object sender, EventArgs e)
    {
        int i;
        int count = Int16.Parse(counttxt.Text.ToString());
        for (i = 1; i <= count; i++)
        {
            AddNewTextBox();
        }
    }

【问题讨论】:

  • 循环遍历Controls 集合并检查每个类型是否为TextBox

标签: c# .net winforms


【解决方案1】:

arraylist 类型的变量中保存对动态生成的TextBox 的引用。

除此之外,如果你想要来自TextBox 的值,名为txt1

string value = this.Controls["txt1"].Text

【讨论】:

    【解决方案2】:
    string allTextBoxValues = "";
    foreach (Control childc in Controls) {
        if (childc is TextBox && childc.Name.Contains("txt"))
            allTextBoxValues += ((TextBox)childc).Text + ",";
    }
    

    【讨论】:

    • Page.Controls 暗示这是 asp.net 页面的解决方案?我怀疑您需要删除第一个 foreach
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    • 2017-01-12
    相关资源
    最近更新 更多