DataGrid合并单元格算法

这段代码展示了如何在DataGrid中实现单元格合并。通过遍历Gridview的每一项,对比相邻单元格内容,当内容相同时隐藏当前单元格并增加前一单元格的RowSpan,以此达到合并效果。实现此功能前,需确保数据已按相关字段排序。

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

        在用Gridview做一些表格的时候可能会用到

 

 

 

  1. private void Unite(DataGrid dgr)
  2. {
  3.  int i;
  4.  string LastType;
  5.  string LastType1;
  6.  int LastCell;
  7.  int LastCell1;
  8.  if (dgr.Items.Count > 0)
  9.  {
  10.     LastType = ((Label)dgr.Items[0].Cells[0].FindControl("deptclass")).Text;
  11.     LastType1 = ((Label)dgr.Items[0].Cells[1].FindControl("deptname")).Text;
  12.     dgr.Items[0].Cells[0].RowSpan = 1;
  13.     dgr.Items[0].Cells[1].RowSpan = 1;
  14.     LastCell = 0;
  15.     LastCell1 = 0;
  16.     for (i = 1; i < dgr.Items.Count; i++)
  17.     {
  18.       if (((Label)dgr.Items[i].Cells[0].FindControl("deptclass")).Text == LastType)
  19.        {
  20.           dgr.Items[i].Cells[0].Visible = false;
  21.           dgr.Items[LastCell].Cells[0].RowSpan++;
  22.        }
  23.       else
  24.        {
  25.           LastType = ((Label)dgr.Items[i].Cells[0].FindControl("deptclass")).Text;
  26.           LastCell = i;
  27.           dgr.Items[i].Cells[0].RowSpan = 1;
  28.        }
  29.       if (((Label)dgr.Items[i].Cells[1].FindControl("deptname")).Text == LastType1)
  30.        {
  31.          dgr.Items[i].Cells[1].Visible = false;
  32.          dgr.Items[LastCell1].Cells[1].RowSpan++;
  33.        }
  34.       else
  35.        {
  36.          LastType1 = ((Label)dgr.Items[i].Cells[1].FindControl("deptname")).Text;
  37.          LastCell1 = i;
  38.          dgr.Items[i].Cells[1].RowSpan = 1;
  39.        }
  40.     }
  41.   }
  42. }

        当然,在实验这个方法的前提是需要对绑定的数据进行按组排序,简单点说就是

        select aa ,bb,cc from abc group by aa,bb,cc 这样才好合并单元格。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值