9

I have sql query in my asp.net webapp and the result is stored in datareader. Every row in datareader contains 10 columns. I want to fill table with these data. However, I have no idea, how to loop through columns in datareader. I need something like this:

while (vysledky.Read())
{
    TableRow row = new TableRow();
    tab.Controls.Add(row);
    foreach (column in ((datareader(row)))  //it is not real code
    {
      TableCell cell = new TableCell();
      cell.Text = datareader(row).content;
      row.Controls.Add(cell);
    }
}

I hope you got the point. Thanks

2 Answers 2

22

Use the FieldCount property of the SqlDataReader:

while (vysledky.Read())
{
    // Iterate over each of the fields (columns) in the datareader's current record
    for (int i = 0; i < vysledky.FieldCount; i++)
    {
        var value = vysledky[i];

        TableCell cell = new TableCell(); 
        cell.Text = Convert.ToString(value); 
        row.Controls.Add(cell); 
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

You should just do it through a SqlDataAdapter:

SqlConnection Conn = new SqlConnection(YourConnectionString);
SqlCommand YourSqlCommand = new SqlCommand();
YourSqlCommand.Connection = Conn;
YourSqlCommand.CommandText = "select * from yourtable";

DataTable dt = new DataTable();

SqlDataAdapter sda = new SqlDataAdapter(YourSqlCommand);

sda.Fill(dt);

At the point, your DataTable (dt) contains all of the data from your query.

3 Comments

Looks like its a ASP table not a DataTable
@Magnus ASP table? I'm not following. That's definitely a DataTable with complete data from the query of the SqlCommand.
@Shark he wants to fill an ASP table not a DataTable. In the question he is referring to TableRow not DataRow

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.