GridView合并列下的行单元格的方法

1.在GridView中要合并单元格,如得到如下效果

  

          可在GridvIew中调的DataBind事件调用下面类中的方法,先在项目的App_Code文件夹下添加下面的类,下面类中写了两个方法,一个是模板列的,一个是普通列的,如果您想合并的是模板列,就调用模板列的方法,如果 您想俣并的是普通列就调用普通列的方法:

                         上面效果就是在DataBind事件中调用右边: UnitCommon.UnitCell( GridView1 , 0 );

类代码如下:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// UnitCommon 的摘要说明
/// </summary>
public class UnitCommon
{
   /// <summary>
   /// 合并行(普通列)
   /// </summary>
   /// <param name=“gv”>所对应的GridView对象</param>
   /// <param name=“columnIndex”>所对应要合并的的索引,从0开始</param>
   public static void UnitCell(GridView gv, int columnIndex)
    {
       int i;
       string lastType;
       int lastCell;
       if (gv.Rows.Count > 0)
        {
           lastType = gv.Rows[0].Cells[columnIndex].Text;
           gv.Rows[0].Cells[columnIndex].RowSpan = 1;
           lastCell = 0;
           for (i = 1; i < gv.Rows.Count; i++)
            {
               if (gv.Rows[i].Cells[columnIndex].Text == lastType)
                {
                   gv.Rows[i].Cells[columnIndex].Visible = false;
                   gv.Rows[lastCell].Cells[columnIndex].RowSpan++;
                 }
                else
                 {
                   lastType = gv.Rows[i].Cells[columnIndex].Text;
                   lastCell = i;
                   gv.Rows[i].Cells[columnIndex].RowSpan = 1;
                 }
            }
        }
    }

    /// <summary>
    /// 合并行(模板列)
    /// </summary>
    /// <param name=“gv”>所对应的GridView对象</param>
    /// <param name=“columnIndex”>所对应要合并的的索引,从0开始</param>
    /// <param name=“lblName”>模板列里面Lable的Id</param>
    public static void UnitCell(GridView gv, int columnIndex, string lblName)
     {
        int i;
        string lastType;
        int lastCell;
        if (gv.Rows.Count > 0)
         {
           lastType = (gv.Rows[0].Cells[columnIndex].FindControl(lblName) as Label).Text;
           gv.Rows[0].Cells[columnIndex].RowSpan = 1;
           lastCell = 0;
           for (i = 1; i < gv.Rows.Count; i++)
            {
              if ((gv.Rows[i].Cells[columnIndex].FindControl(lblName) as Label).Text == lastType)
               {
                 gv.Rows[i].Cells[columnIndex].Visible = false;
                 gv.Rows[lastCell].Cells[columnIndex].RowSpan++;
               }
              else
               {
                 lastType = (gv.Rows[i].Cells[columnIndex].FindControl(lblName) as Label).Text;
                 lastCell = i;
                 gv.Rows[i].Cells[columnIndex].RowSpan = 1;
               }
            }
        }
     }

}

原文地址:https://www.cnblogs.com/yingger/p/2621324.html