Search code examples
c#asp.netdatareader

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).Can you tell me how to display in multiple rows.


Solution

  • 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?