我需要动态创建控件并在其中显示一些数据库值。 现在我做了:
SqlCommand cmdBE = new SqlCommand("SELECT COUNT (type) FROM composants_test WHERE type = 'BE' AND codeArticlePF LIKE'%" + motcle + "%' ", con);
Int32 countBE = (Int32) cmdBE.ExecuteScalar();
Console.WriteLine("nb BE : " +countBE);
SqlCommand cmdBEName = new SqlCommand("SELECT codeArticleComposant FROM composants_test WHERE type = 'BE' AND codeArticlePF LIKE'%" + motcle + "%'", con);
SqlDataReader readerBE = cmdBEName.ExecuteReader();
if (readerBE.Read())
{
Console.WriteLine(readerBE["codeArticleComposant"].ToString());
int pointXBE = 20;
int pointYBE = 20;
panelBE.Controls.Clear();
panelBE.Focus();
for (int i = 0; i < countBE; i++)
{
TextBox textBoxBE = new TextBox();
Label labelBE = new Label();
textBoxBE.Name = "textBoxBE" + i;
textBoxBE.Text = readerBE["codeArticleComposant"].ToString();
textBoxBE.Location = new Point(pointXBE + 35, pointYBE);
textBoxBE.CharacterCasing = CharacterCasing.Upper;
textBoxBE.Width = 150;
labelBE.Text = "BE" + (i + 1).ToString() + " : ";
labelBE.Location = new Point(pointXBE, pointYBE);
panelBE.Controls.Add(textBoxBE);
panelBE.Controls.Add(labelBE);
panelBE.Show();
pointYBE += 30;
}
readerBE.Close();
}
我的问题是如果创建了几个控件,那么#34; readerBE [&#34; codeArticleComposant&#34;]。ToString()&#34;不会改变。 如何让它循环我需要的不同结果呢?
答案 0 :(得分:1)
您实际上需要继续阅读,直到使用While
循环读取所有记录,因此请将if
更改为While
,如:
int i =0; // use local variable for generating controls unique names
While(readerBE.Read())
{
//............
//........... your code here
TextBox textBoxBE = new TextBox();
Label labelBE = new Label();
textBoxBE.Name = "textBoxBE" + i;
textBoxBE.Text = readerBE["codeArticleComposant"].ToString();
textBoxBE.Location = new Point(pointXBE + 35, pointYBE);
textBoxBE.CharacterCasing = CharacterCasing.Upper;
textBoxBE.Width = 150;
labelBE.Text = "BE" + (i + 1).ToString() + " : ";
labelBE.Location = new Point(pointXBE, pointYBE);
panelBE.Controls.Add(textBoxBE);
panelBE.Controls.Add(labelBE);
panelBE.Show();
i++; // increment after each read
}