【问题标题】:Populate dynamically created textboxes with SQL query使用 SQL 查询填充动态创建的文本框
【发布时间】:2018-02-15 14:05:18
【问题描述】:

我需要动态创建控件并在其中显示一些数据库值。 现在我做到了:

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

我的问题是,如果创建了几个控件,“readerBE[”codeArticleComposant“].ToString()”不会改变。

如何让它循环显示我需要的不同结果?

【问题讨论】:

  • 使用 CheckBoxList 并将数据绑定到它不是更好吗,例如所示here

标签: c# sql-server winforms


【解决方案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

}

【讨论】:

  • 好吧,一个while循环和一些调整让它像我想要的那样工作。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-11
相关资源
最近更新 更多