GridView合并单元格

   近日在做一个项目的时候,需要合并单元格的内容,其实网上也有很多这方面的资料,

但这些都是判断下一行的内容是否相同,然后决定是否合并。而我需要判断前面若干列单元格

以及下行的内容相同才合并。

 

先看一下效果:

  《GridView合并单元格》

 

实现代码如下:

 

”’ <summary> ”’ 合并GridView ”’ </summary> ”’ <param name=”gv”>GridView</param> ”’ <param name=”startCol”>起始列</param> ”’ <param name=”endCol”>终止列</param> ”’ <remarks></remarks> Public Shared Sub GroupRows(ByVal gv As GridView, ByVal startCol As Integer, ByVal endCol As Integer) Dim i As Integer = 0, rowSpanNum As Integer = 1 Dim flag As Boolean = True ‘前面列的值是否相等 Dim k As Integer Dim x, y As Integer ‘判断第3列辅助 Dim rowIndex As Integer ‘列号 For rowIndex = endCol To startCol Step -1 i = 0 rowSpanNum = 1 While i < gv.Rows.Count – 1 x = 0 ‘判断第3列辅助 y = 0 ‘判断第3列辅助 Dim gvr As GridViewRow = gv.Rows(i) i += 1 flag = True While i < gv.Rows.Count x = i – 1 ‘判断第3列辅助 y = x + 1 ‘判断第3列辅助 Dim gvrNext As GridViewRow = gv.Rows(i) ‘判断当前行前面列的值是否相等 For k = rowIndex To startCol Step -1 ‘如果是第3列,则判断ReportsID If rowIndex <= 3 Then If gv.DataKeys(x).Value <> gv.DataKeys(y).Value Then flag = False Exit For End If Else If gvr.Cells(k).Text <> gvrNext.Cells(k).Text Then flag = False Exit For End If End If Next If flag Then gvrNext.Cells(rowIndex).Visible = False rowSpanNum += 1 Else gvr.Cells(rowIndex).RowSpan = rowSpanNum rowSpanNum = 1 Exit While End If If i = gv.Rows.Count – 1 Then gvr.Cells(rowIndex).RowSpan = rowSpanNum End If i += 1 End While End While Next End Sub 

 

在GridView的DataBound事件调用即可:

Protected Sub gvLists_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvLists.DataBound GroupRows(gvLists, 1, 8) End Sub 

 

其中有代码:

 If rowIndex <= 3 Then

 这是因为下一个报告的日期或分部有可能与当前行的值相同

 

大家可以根据自己实际的需要进行修改。

如有不当之处,还请指正。谢谢!

 

 

    原文作者:yyj135
    原文地址: https://blog.csdn.net/yyj135/article/details/5026153
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞