csgashine

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
    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.
  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.
    This example used a table because it gave a good opportunity to show how child controls (cells
and rows) are added to the Controls collection of the parent, but of course this mechanism works
with any other server control.
posted on 2006-03-22 17:54  asp-shine  阅读(183)  评论(0编辑  收藏  举报