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. row.Cells.Add(cell); }
// Add the row to the table. table1.Rows.Add(row); }
// Add the table to the page. this.Controls.Add(table1); }
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: greeny_1984 13 May 2009 | Member Level: Diamond Points : 0 |
Hi,
good code snippet
Nicely explained
regards,
greeny
|