Winforms 如何将动态添加的文本框中的数据读取到FlowLayoutPanel?

Winforms 如何将动态添加的文本框中的数据读取到FlowLayoutPanel?,winforms,c#-4.0,textbox,flowlayoutpanel,Winforms,C# 4.0,Textbox,Flowlayoutpanel,我从SQL表中动态地在FlowlayoutPanel中添加了文本框,如下所示 string query = "SELECT* FROM tblA"; using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=DummyData;Integrated Security=True")) { conn.Open(); using (SqlCommand cmd = new SqlComm

我从SQL表中动态地在FlowlayoutPanel中添加了文本框,如下所示

string query = "SELECT* FROM tblA";

using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=DummyData;Integrated Security=True"))
{
    conn.Open();

    using (SqlCommand cmd = new SqlCommand(query, conn))
    {
        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            Label objLbl = new Label();
            TextBox objText = new TextBox();
            objLbl.Text = reader["A_Name"].ToString();
            objText.Name = "txt"+reader["ID"].ToString();
            pnlFlow.Controls.Add(objLbl);
            pnlFlow.Controls.Add(objText);
        }
    }
}

很好用。现在我面临的问题是当用户在这些文本框中输入一些数据时。如何获取这些数据以进行进一步处理?

根据需要获取值的方式和时间,可以采用多种方法

如果您需要同时阅读所有内容,请执行以下操作:

foreach(Control c in pnlFlow.Controls)
{
      if c.Name.StartsWith("txt")
      // process the text box
      // you might want to use a more distinct naming pattern to be safe
      ...
}
如果需要在不同时间单独处理它们,可以在控件集合中按名称引用它们:

string textBoxName = "txt12345";
string valueText = ((TextBox)pnlFlow.Controls[textBoxName]).Text;
当然,这两个代码段都需要更好的错误处理,但我将把这留给您