GridView多行表头合并

本文详细介绍了在ASP.NET中使用GridView组件实现多行表头合并的方法。通过清除默认表头并重新创建自定义表头,利用ColumnSpan和RowSpan属性,实现了复杂表头布局。适用于需要在网页上展示复杂表格数据的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

多行表头合并, 网上很多实例, 这里写的很详细, 力求让每个人都能看懂. 实现原理:GridView在ASP.NET中最终转为HMTL的表格显示表头。 在GridView创建行表头行时: e.Row.RowType == DatacontrolRowType.Header 清除掉旧的表头, 再重新拼接新的表头.

TableHeaderCell thc = new TableHeaderCell();

thc.Text = "表头";

对应生成的HTML为:<th>表头</th>

多行表头合并效果图

测试多行合并表头
表头表头1表头2表头3
表头1-1表头2-1表头2-2表头3-1表头3-2

表头3-3

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        //判断创建的行是否为表头行
        if (e.Row.RowType == DataControlRowType.Header)
        {
            //获取表头所在行的所有单元格
            TableCellCollection tcHeader = e.Row.Cells;
            //清除自动生成的表头
            tcHeader.Clear();

            //新添加的第一个表头单元格, 设置为合并7个列, 从而形成一行.
            tcHeader.Add(new TableHeaderCell());
            tcHeader[0].ColumnSpan = 7;
            tcHeader[0].Text = "测试多行合并表头</th></tr><tr>";
            //</th>表示当前单元格结束, </tr>表示本行结束, <tr>另起新一行    关键点
            
            //添加第二个表头单元格, 设置为合并两行.
            tcHeader.Add(new TableHeaderCell());
            tcHeader[1].RowSpan = 2;
            tcHeader[1].Text = "表头";

            tcHeader.Add(new TableHeaderCell());
            tcHeader[2].Text = "表头1";

            tcHeader.Add(new TableHeaderCell());
            tcHeader[3].ColumnSpan = 2;
            tcHeader[3].Text = "表头2";

            tcHeader.Add(new TableHeaderCell());
            tcHeader[4].ColumnSpan = 3;
            tcHeader[4].Text = "表头3</th></tr><tr>";
            
            //第二行的所有的单元格添加完成, 换行</th></tr><tr>

            //添加第三行所有的单元格
              tcHeader.Add(new TableHeaderCell());
            tcHeader[5].Text = "表头1-1";

            tcHeader.Add(new TableHeaderCell());
            tcHeader[6].Text = "表头2-1";

            tcHeader.Add(new TableHeaderCell());
            tcHeader[7].Text = "表头2-2";

            tcHeader.Add(new TableHeaderCell());
            tcHeader[8].Text = "表头3-1";

            tcHeader.Add(new TableHeaderCell());
            tcHeader[9].Text = "表头3-2";

            tcHeader.Add(new TableHeaderCell());
            tcHeader[10].Text = "表头3-3</th></tr><tr>";
        }

    }

  

转载于:https://www.cnblogs.com/ileaves/archive/2012/06/03/2532433.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值