合并GridView中某列(含模板列)相同信息的行(单元格)




在做一个项目时,需要合并gridview中相同信息的列,于是google了一下,发现了下面的这个例子:


http://blog.csdn.net/images/blog_csdn_net/quou2002/191571/r_1.JPG

http://blog.csdn.net/images/blog_csdn_net/quou2002/191571/r_2.JPG


解决方法如下(写在公共模块里,定义为静态方法方便调用):

1 /// <summary>
2 /// 合并GridView中某列相同信息的行(单元格)
3 /// </summary>
4 /// <param name="GridView1">GridView</param>
5 /// <param name="cellNum">第几列</param>
6 public static void GroupRows(GridView GridView1, int cellNum)
7 {
8 int i = 0, rowSpanNum = 1;
9 while (i < GridView1.Rows.Count - 1)
10 {
11 GridViewRow gvr = GridView1.Rows[i];
12
13 for (++i; i < GridView1.Rows.Count; i++)
14 {
15 GridViewRow gvrNext = GridView1.Rows[i];
16 if (gvr.Cells[cellNum].Text == gvrNext.Cells[cellNum].Text)
17 {
18 gvrNext.Cells[cellNum].Visible = false;
19 rowSpanNum++;
20 }
21 else
22 {
23 gvr.Cells[cellNum].RowSpan = rowSpanNum;
24 rowSpanNum = 1;
25 break;
26 }
27
28 if (i == GridView1.Rows.Count - 1)
29 {
30 gvr.Cells[cellNum].RowSpan = rowSpanNum;
31 }
32 }
33 }
34 }
35
36


但是当我把代码拷贝到我的项目中时,却怎么也不能得到想要的结果,相当于上面例子中全部都变成了金马店 ,于是将代码重新读了一遍,发现没有什么问题百思不得其解,郁闷了好半天后,才发现,上面例子中的cells[cellNum].text 取的是row中的值,而需要合并的是一个模板列中的lable,经修改:


 


        int i = 0,rowSpanNum = 1;
        int cellNum = 0; //此处cellnum的值为你想要合并的列的索引,从0开始
        while (i < GridView1.Rows.Count - 1)
        {
            GridViewRow gvr = GridView1.Rows[i];
           
            Label tmplable = (Label)gvr.FindControl("UpUnitName");
           
            for (++i; i < GridView1.Rows.Count; i++)
            {
                GridViewRow gvrNext = GridView1.Rows[i];
                Label tmplable1 = (Label)gvrNext.FindControl("UpUnitName");



                if (tmplable.Text == tmplable1.Text)
                {
                    gvrNext.Cells[cellNum].Visible = false;
                    rowSpanNum++;
                }
                else
                {
                    gvr.Cells[cellNum].RowSpan = rowSpanNum;
                    rowSpanNum = 1;
                    break;
                }


                if (i == GridView1.Rows.Count - 1)
                {
                    gvr.Cells[cellNum].RowSpan = rowSpanNum;
                }
            }

posted @ 2011-06-22 16:00  你妹的sb  阅读(474)  评论(2编辑  收藏  举报
百度一下