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

2 Answers 2

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; 
    }
}
Sign up to request clarification or add additional context in comments.

Comments

-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.

2 Comments

Yes, but how do I dynamically create a button for each row in the DB
You really should either try to answer the question, or just not post an answer at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.