Create Html Table Dynamically

The following code dynamically creates a table with five rows and four cells per
row, sets their colors and text, and shows all this on the page. The interesting detail is that no control tags are declared in the .aspx file. Instead, everything is generated programmatically.

protected void Page_Load(object sender, System.EventArgs e)
// Create a new HtmlTable object.
HtmlTable table1 = new HtmlTable();

// Set the table's formatting-related properties.
table1.Border = 1;
table1.CellPadding = 3;
table1.CellSpacing = 3;
table1.BorderColor = "red";

// Start adding content to the table.
HtmlTableRow row;
HtmlTableCell cell;
for (int i=1; i<=5; i++)
// Create a new row and set its background color.
row = new HtmlTableRow();
row.BgColor = (i%2==0 ? "lightyellow" : "lightcyan");
for (int j=1; j<=4; j++)
// Create a cell and set its text.
cell = new HtmlTableCell();
cell.InnerHtml = "Row: " + i.ToString()+ "<br />Cell: " + j.ToString();
// Add the cell to the current row.

// Add the row to the table.

// Add the table to the page.

This example contains two nested loops. The outer loop creates a row. The inner loop then creates the cells and adds them to the Cells collection of the current row. When the inner loop ends, the code adds the entire row to the Rows collection of the table. The final step occurs when the outer loop is finished. At this point, the code adds the completed table to the Controls collection of the page.


Author: PHANI HARSHITHA MADALA13 May 2009 Member Level: Gold   Points : 0


good code snippet

Nicely explained



Guest Author: av04 Mar 2012

I converted this code to and ran it. table is not getting displayed. What do i do to get the table ?

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: