明天的明天 永远的永远 未知的一切 我与你一起承担 ??

是非成败转头空 青山依旧在 几度夕阳红 。。。
随笔 - 1277, 文章 - 0, 评论 - 214, 阅读 - 321万
  博客园  :: 首页  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

asp.net中合并DataGrid行

Posted on   且行且思  阅读(826)  评论(0编辑  收藏  举报
 

例如:

序号            名称      计量单位
一、工业经济    aaa       万元
一、工业经济    bbb       个

合并为:

序号            名称      计量单位
一、工业经济    aaa       万元
                bbb       个
只是将第一列的多行合并为一行,怎么实现?谢谢大家了先!

 

实现方法:
把笨狼哥的改成这样试试:
在.aspx页面,<asp:datagrid>中用
OnPreRender="fDGrid_PreRender">

在.cs文件:

 //合并相同的单元格
  public void fDGrid_PreRender(object sender, System.EventArgs e)
  {
   if(this.fDGrid.Items.Count <=1)
   {
    return;
   }
   col=0;
    TableCell oldtc = this.fDGrid.Items[0].Cells[col];
    for(int i=1;i<this.fDGrid.Items.Count;i++)
    {
     TableCell tc = this.fDGrid.Items[i].Cells[col];
     if(tc.Text == oldtc.Text)
     {
      tc.Visible = false;
      if(oldtc.RowSpan == 0)
      {
       oldtc.RowSpan = 1;
      }
      oldtc.RowSpan = oldtc.RowSpan +1;
      oldtc.VerticalAlign = VerticalAlign.Middle;
     }
     else
     {
      oldtc = tc;
     }
    }
  }

当然,还可以用ItemDataBound事件来处理。具体细节如下

在.cs文件中的
InitializeComponent方法中加入:
  
 this.dgContacts.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgContacts_ItemDataBound);

在.cs文件中的Page_Load中加入:
if (!Page.IsPostBack )
{
lastIndex=0;
}

其中dgContacts为DataGrid的名字

再在 .cs文件中加入下面的代码:
         int lastIndex;
 protected void dgContacts_ItemDataBound(object source,
   System.Web.UI.WebControls.DataGridItemEventArgs e)
  {
   if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
   {
    string isManager = (string)DataBinder.Eval(e.Item.DataItem, "序号");
    int inn=e.Item.ItemIndex;
    TableCell c;
                                     int col=0;
    if (inn>0)
    {
     if(dgContacts.Items[lastIndex].Cells[col].Text==isManager)
     {
      
      c=new TableCell();
      c=e.Item.Cells[col];
      if(dgContacts.Items[lastIndex].Cells[col].RowSpan==0)
           dgContacts.Items[lastIndex].Cells[col].RowSpan=1;

      dgContacts.Items[lastIndex].Cells[col].RowSpan+=1;
      
      Response.Write(dgContacts.Items[lastIndex].Cells[col].RowSpan);
      e.Item.Cells.Remove(c);
      
     }
     else
     {
      e.Item.Cells[col].Text=isManager;
      lastIndex=e.Item.ItemIndex;
     }
    }
    else
    {
     e.Item.Cells[col].Text=isManager;
    }
    
   }
  }

两种方法都可以,但是还是第一中方法好,通用性也强,第二种方法如果稍加修改,应该也可以。可能还有其他方法。具体用那种方法不重要,重要的是如何灵活应用基本的知识解决复杂的问题。

编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示