我已经像这样从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;
当然,两个片段都需要更好的错误处理,但我将留给您。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句