如何从动态创建的文本框中获取数据(windows应用程序)



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

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();
        }
    }

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

除此之外,如果您想要TextBox中命名为txt1的值

string value = this.Controls["txt1"].Text
string allTextBoxValues = "";
foreach (Control childc in Controls) {
    if (childc is TextBox && childc.Name.Contains("txt"))
        allTextBoxValues += ((TextBox)childc).Text + ",";
}

最新更新