Liam12
Liam12

Reputation: 1

How to loop through a database table and create a button for column

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

Upvotes: 0

Views: 560

Answers (2)

Bosco
Bosco

Reputation: 1554

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

Upvotes: 3

Mr.Malte
Mr.Malte

Reputation: 27

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.

Upvotes: -2

Related Questions