0

I am trying to loop through a DB and create a button for each row based on my query. I should be getting 3 buttons in return however only one is being created.

 DataTable dt = new DataTable();
 con.Open();
 string TeamID = (string)Session["TeamID"];
 SqlDataReader myReader = null;
 SqlCommand myCommand = new SqlCommand("SELECT * FROM Players1 WHERE 
 TeamID = " + teamID, con);
 myCommand.Parameters.AddWithValue("@TeamID", TeamID);
 myReader = myCommand.ExecuteReader();
 while (myReader.Read())
 {
   foreach (Object ob in myReader)
 {
  Button1.Text = "" + (myReader["Name"].ToString());
  }
 }

I should be getting 3 buttons based on the data in my DB

Liam12
  • 1
  • 1

2 Answers2

3

You need to create or instantiate the Button object itself, and then assign value to it.

about getting data from your myReader object see this

DataTable dt = new DataTable();
con.Open();
string TeamID = (string)Session["TeamID"];
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("SELECT * FROM Players1 WHERE 
TeamID = " + teamID, con);
myCommand.Parameters.AddWithValue("@TeamID", TeamID);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
    foreach (Object ob in myReader)
    {
        Button btn = new Button();
        btn.ID = "Btn_" + ob["Id"]; //I assume the table has an Id
        btn.Text = ob["Name"]; //I also assume the table has a Name column
        //for click events
        //btn.Click = btn_Click_Event; 
    }
}
Bosco
  • 1,536
  • 2
  • 13
  • 25
-2

I dunno exactly where you should be getting three buttons. From what it looks like, you're just changing the text of Button1, which is a single button. You're changing the text of Button1 three times. You want Button2 and Button3 to change as well, I guess.

Mr.Malte
  • 27
  • 1