使用HtmlControl动态创建一个表格

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
 
public partial class Chapter04_CreateTableByCode : System.Web.UI.Page
{
    // 使用Html服务器控件创建一个5行4列的表格
    protected void Page_Load(object sender, EventArgs e)
    {
        HtmlTable table = new HtmlTable();
        table.Border = 1;
        table.CellSpacing = 3;
        table.CellPadding = 3;
        table.BorderColor = "red";
 
        HtmlTableRow row;
        HtmlTableCell cell;
        for (int i = 1; i <= 5; i++)
        {
            row = new HtmlTableRow();
            row.BgColor = i % 2 == 0 ? "lightyellow" : "lightcyan";
            for (int j = 1; j <= 4; j++)
            {
                cell = new HtmlTableCell();
                cell.InnerHtml = "Row : " + i.ToString() + "<br />Cell: " + j.ToString();
                row.Cells.Add(cell);
            }
            table.Rows.Add(row);
        }
        this.Controls.Add(table);
    }
}

效果:

image

posted on 2012-07-06 15:46  SkySoot  阅读(1107)  评论(0编辑  收藏  举报

导航