http://blog.163.com/hwb_1988/blog/static/175678127201011110460568/
所需控件:两个文本框,一个命令按钮,一个Table控件
正常的运行效果如下:
如果文本框没有输入数据,则运行效果如下:
Default.aspx.cs中的代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Focus();
Table1.Width = 400;
Table1.Caption = "动态生成表格";
Table1.GridLines = GridLines.Both; //设置单元格的框线
Table1.HorizontalAlign = HorizontalAlign.Center;//设置表格相对页面居中
Table1.CellPadding = 0; //设置单元格内间距
Table1.CellSpacing = 0; //设置单元格之间的距离
Table1.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
Table1.Visible = true;
if (TextBox1.Text == "" || TextBox2.Text == "")
{
Table1.Caption = "必须输入行、列数!";
return;
}
int iRows = int.Parse(TextBox1.Text);
int iCells = int.Parse(TextBox2.Text);
for (int i=0; i < iRows; i++)
{
TableRow myRow = new TableRow();
for (int j=0; j < iCells; j++)
{
TableCell myCell = new TableCell();
myCell.Text = i.ToString() + "," + j.ToString();
myRow.Cells.Add(myCell);
}
Table1.Rows.Add(myRow);
}
string[] myArray = new string[4];
myArray[0] = "单击进入“网易”";
myArray[1] = "单击进入“搜狐”";
myArray[2] = "单击进入“新浪”";
myArray[3] = "单击进入“百度”";
string[] myLink = new string[4];
myLink[0] = "http://www.163.com";
myLink[1] = "http://www.sohu.com";
myLink[2] = "http://www.sina.com.cn";
myLink[3] = "http://www.baidu.com";
for (int i = 0; i <= 3; i++)
{
TableRow myRow = new TableRow();
TableCell myCell=new TableCell();
myCell.ColumnSpan=iCells; //ColumnSpan 属性用于设置或返回在 Table 控件中 TableCell 横跨的列数。
HyperLink lyp=new HyperLink();
lyp.Text=myArray[i];
lyp.NavigateUrl=myLink[i];
lyp.Target="_blank";
myCell.Controls.Add(lyp);
myRow.Cells.Add(myCell);
Table1.Rows.Add(myRow);
}
}
}