//定义表头
TableRow trHead = new TableRow();
//定义列
TableCell tcHead = new TableCell();
//设置列名
tcHead.Text = "列名1";
//追加一个列
trHead.Cells.Add(tcHead);
tcHead = new TableCell();
//设置列名
tcHead.Text = "列名2";
//追加一个列
trHead.Cells.Add(tcHead);
for (int i = 0; i < 循环变量; i++)
{
tcHead = new TableCell();
//设置列名
tcHead.Text = "列名";
//追加一个列
trHead.Cells.Add(tcHead);
}
//追加表头
tabStudentScore.Rows.Add(trHead);
添加列的时候还可以添加控件
//LinkButton
tcHead = new TableCell();
LinkButton lnb = new LinkButton();
lnb.Text = "按钮名称";
lnb.ToolTip = "悬浮提示信息";
lnb.OnClientClick = "JS方法名;";
lnb.CssClass = "样式名称";
//将LinkButton追加到列中
tcHead.Controls.Add(lnb);
//追加一个列
trHead.Cells.Add(tcHead);
tabStudentScore为.net的Table控件
<asp:Table ID="tabStudentScore" runat="server" BorderWidth="0" GridLines="Horizontal"></asp:Table>
循环添加明细行
for (int i = 0; i < 明细行数; i++)
{
for (int j = 0; j < dtHead.Rows.Count; j++)
{
TableCell tc = new TableCell();
//创建一个文本框
txt = new TextBox();
txt.Width = 100;
txt.ID = "txt" + i.ToString() + (j).ToString();
txt.CssClass = "chkNum";
//txt.Text = "显示内容"
//将文本框追加到列中
tc.Controls.Add(txt);
//追加一个列(文本框,用于输入)
dr.Cells.Add(tc);
}
}
//追加表明细行
tabStudentScore.Rows.Add(dr);
动态构建的表就完成了,接下来就是页面提交后,后台是如何取得表格中文本框输入的值。
for (int row = 0; row < intRowCount; row++)
{
for (int cell = 1; cell < intCellCount; cell++)
{
Request.Form["txt" + row.ToString() + cell.ToString()].ToString()
}
}