HtmlTable
HtmlTable table = new HtmlTable(); //創建表格
for (int i = 0; i < 5; i++)
{
HtmlTableRow row = new HtmlTableRow(); //控制行
for (int j = 0; j < 5; j++)
{
HtmlTableCell cell = new HtmlTableCell(); //控制單元格
cell.InnerText = "123"; //單元格內的文本,相當於<td>123</td>
row.Cells.Add(cell); //將創建的單元格對象,添加到指定行內
}
table.Rows.Add(row); //將創建的行對象,添加到行的集合中
}
this.Controls.Add(table); //將創建的表,添加到集合
table
Table t = new Table(); //創建表
for (int i = 0; i < 3; i++)
{
TableRow row = new TableRow(); //創建行
for (int j = 0; j < 3; j++)
{
TableCell cell = new TableCell(); //單元格
Button btn = new Button(); //創建按鈕
btn.Text = "123"; //按鈕的Text爲123
cell.Controls.Add(btn); //將按鈕添加到單元格內
row.Cells.Add(cell); //將創建的單元格對象,添加到指定行內
}
t.Rows.Add(row); //將創建的行對象,添加到行的集合中
//button是服務器控件,必須放在具有 runat=server 的窗體標記內。 }
this.Panel1.Controls.Add(t); //將表添加到panel容器中
DataTable
DataTable dt = new DataTable();//創建表
DataColumn dc = new DataColumn();//創建列
dc.ColumnName = "id"; //列名id
dc.DataType = typeof(int); //列的數據類型,也可以寫成dc.DataType = Type.GetType("System.Int32");
dc.AllowDBNull = false; //此列是否允許爲空
dc.AutoIncrement = true; //是否爲自動增長列
dc.AutoIncrementSeed = 1; //起始值爲1
dc.AutoIncrementStep = 1; //增量爲1
dt.Columns.Add(dc); //將列添加到表中
dc = new DataColumn();
dc.ColumnName = "name";
dc.DataType = typeof(string);
dc.AllowDBNull = false;
dt.Columns.Add(dc);
DataRow row = dt.NewRow(); //創建行(用表名.NewRow()方法,不是new DataRow())
row["name"] = "zhangsan"; //向表中添加數據,[]裏的字符串要與列對應
dt.Rows.Add(row); //將行添加到表中
//將表中的數據綁定到GridView中
this.GridView1.DataSource = dt;
this.GridView1.DataBind();