0

I need to dynamically create controls and display some database values in them. For now I did :

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

My problem is that if several Controls are created, "readerBE["codeArticleComposant"].ToString()" does not change.

How can I make it loop on the different results that I need ?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
A. Petit
  • 158
  • 3
  • 14
  • Wouldn't it be better to use a CheckBoxList and bind the data to it, eg as shown [here](https://stackoverflow.com/questions/7485631/winforms-how-to-bind-the-checkbox-item-of-a-checkedlistbox-with-databinding)? – Panagiotis Kanavos Feb 15 '18 at 14:12

1 Answers1

1

You actually need to keep reading until all the records are being read using While loop, so change your if to While like:

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

}
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160