Displaying records in a table in asp.net
conn.Open();
TableRow r = new TableRow();
TableCell c = new TableCell();
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
c.Controls.Add(new LiteralControl(reader["Name"].ToString()));
r.Cells.Add(c);
Table1.Rows.Add(r);
c.Controls.Add(new LiteralControl(reader["RollID"].ToString()));
r.Cells.Add(c);
Table1.Rows.Add(r);
}
I'm using the above code to print data in table.But all fields are coming in a single row(Row not incrementing).Ca开发者_JAVA百科n you tell me how to display in multiple rows.
At the moment, you are creating a single row and cell, and adding all of your controls to that single cell.
While what you want is certainly possible (just make sure you create a new cell for each data element you pull out of your reader, and a new row for each iteration through the while loop), is there a reason you aren't using something like a GridView
to present this content?
Create a new instance of TableRow for each row. You're just creating 1 instance before iterating through the resultset.
Move your construction of the TableCell and TableRow variables inside of your WHILE loop, at the top. In this way, you will get a new row and a new cell for each record in the reader.
Consider code that looks like the following (the comments are mine):
conn.Open();
// MOVE THESE
/**
TableRow r = new TableRow();
TableCell c = new TableCell();
**/
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
// TO HERE.. so that a new row and cell are created for each record in your reader
TableRow r = new TableRow();
TableCell c = new TableCell();
c.Controls.Add(new LiteralControl(reader["Name"].ToString()));
r.Cells.Add(c);
//Table1.Rows.Add(r); -- ADD THE ROW AFTER THE SECOND FIELD... THEN YOU HAVE 2 COLUMNS
c.Controls.Add(new LiteralControl(reader["RollID"].ToString()));
c = new TableCell(); // CREATE A NEW CELL, FOR A NEW COLUMN
r.Cells.Add(c);
Table1.Rows.Add(r);
}
精彩评论