`

看孟子的《ASP.NET 2.0中合并 GridView 的表头单元格》

阅读更多
ASP.NET 2.0中合并 GridView 的表头单元格
今天看了孟子《ASP.NET 2.0中合并 GridView 的表头单元格》的特效,感觉还不错。
在他的基础上我做了裁减把他的核心部分拉出来解释一下
代码如下:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.BackColor = System.Drawing.Color.DarkOrange;
GridView1.DataSource = CreateDataSource();
GridView1.DataBind();
}
}
ICollection CreateDataSource()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("学生姓名", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("语文", typeof(System.Decimal)));
dt.Columns.Add(new System.Data.DataColumn("数学", typeof(System.Decimal)));
dt.Columns.Add(new System.Data.DataColumn("英语", typeof(System.Decimal)));
for (int i = 0; i < 8; i++)
{
Random rd = new Random(Environment.TickCount * i);
dr = dt.NewRow();
dr[0] = "学生" + i.ToString();
dr[1] = System.Math.Round(rd.NextDouble() * 100, 2);
dr[2] = System.Math.Round(rd.NextDouble() * 100, 2);
dr[3] = System.Math.Round(rd.NextDouble() * 100, 2);
dt.Rows.Add(dr);
}
System.Data.DataView dv = new DataView(dt);
return dv;
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow rowHeader = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
TableCellCollection cells = e.Row.Cells;
TableCell headerCell = new TableCell();
headerCell.Text = "";
rowHeader.Cells.Add(headerCell);
headerCell = new TableCell();
headerCell.Text = "学生成绩";
headerCell.ColumnSpan = cells.Count - 1;
headerCell.HorizontalAlign = HorizontalAlign.Center;
rowHeader.Cells.Add(headerCell);
rowHeader.Visible = true;
GridView1.Controls[0].Controls.AddAt(0, rowHeader);
}
}
这里我想讲2点(个人认为还只得关注的东西,也是他的代码只得看的几处)
1. ICollection CreateDataSource()方法
他告诉我们:
l GridView支持所有实现了ICollection接口类型的数据源
l DataView实现了ICollection接口而DataTable没有,但DataTable 实现了IListSource 接口GridView也支持实现IListSource 接口的数据源。
2. protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) 方法
l 在记录被添加后的操作(这是本例的重要核心方法)
其实所以的表格绑定控件他都是一个Table,孟子的表头特效也就是修改了 Table 标记中第一个Tr 标记内的表现形式而已,再通过单元格的合并达到合并效果,从中我们能联想出其他的应用,这里不多说了大家尽情发挥吧!
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics