代码改变世界

GridView 控件合并表头学习。

2011-05-24 13:54  温森特  阅读(367)  评论(0编辑  收藏  举报

如果想要实现如下图所示的GridView表头,怎样做呢?其实很简单,我们只需要在后台代码中RowCreated(object sender, GridViewRowEventArgs e)事件中动态的添加表头就可以了,直接上代码,一看就明白。主要注意的就是,表头的创建顺序,由上而下的创建。

 

 
if (e.Row.RowType == DataControlRowType.Header)
                {
                    TableCellCollection cellHeaders 
= e.Row.Cells;
                    cellHeaders.Clear();

                    cellHeaders.Add(
new TableHeaderCell());
                    cellHeaders[
0].RowSpan = 2;
                    cellHeaders[
0].Text = "";

                    cellHeaders.Add(
new TableHeaderCell());
                    cellHeaders[
1].ColumnSpan = 2;
                    cellHeaders[
1].Text = "Peak In Range %";

                    cellHeaders.Add(
new TableHeaderCell());
                    cellHeaders[
2].ColumnSpan = 2;
                    cellHeaders[
2].Text = "Non-Peak In Range %";

                    cellHeaders.Add(
new TableHeaderCell());
                    cellHeaders[
3].ColumnSpan = 2;
                    cellHeaders[
3].Text = "Total In Range %";
                                       

                    cellHeaders.Add(
new TableHeaderCell());
                    cellHeaders[
4].RowSpan = 2;
                    cellHeaders[
4].Text = "Peak Hours <br/>History</th></tr><tr>";

                    cellHeaders.Add(
new TableHeaderCell());
                    cellHeaders[
5].Attributes.Add("style""color:White;background-color:#7FA3B8;white-space:nowrap;");
                    cellHeaders[
5].Text = "Forecast %";

                    cellHeaders.Add(
new TableHeaderCell());
                    cellHeaders[
6].Attributes.Add("style""color:White;background-color:#7FA3B8;white-space:nowrap;");
                    cellHeaders[
6].Text = "Actual %";

                    cellHeaders.Add(
new TableHeaderCell());
                    cellHeaders[
7].Attributes.Add("style""color:White;background-color:#7FA3B8;white-space:nowrap;");
                    cellHeaders[
7].Text = "Forecast %";

                    cellHeaders.Add(
new TableHeaderCell());
                    cellHeaders[
8].Attributes.Add("style""color:White;background-color:#7FA3B8;white-space:nowrap;");
                    cellHeaders[
8].Text = "Actual %";

                    cellHeaders.Add(
new TableHeaderCell());
                    cellHeaders[
9].Attributes.Add("style""color:White;background-color:#7FA3B8;white-space:nowrap;");
                    cellHeaders[
9].Text = "Forecast %";

                    cellHeaders.Add(
new TableHeaderCell());
                    cellHeaders[
10].Attributes.Add("style""color:White;background-color:#7FA3B8;white-space:nowrap;");
                    cellHeaders[
10].Text = "Actual %";

                }