现在的位置: 首页 > 综合 > 正文

GridView控件合并指定单元格的方法

2013年07月09日 ⁄ 综合 ⁄ 共 1957字 ⁄ 字号 评论关闭

    写了一个合并GridView控件单元格的方法,比较好用。不用修改代码,拷贝后直接就可以使用。

     /// <summary>
    /// 合并单元格方法
    /// </summary>
    /// <param name="iColumns">第几列数据相同</param>
    private void MergeGridCell(int iColumns)
    {
        //合并的行数
        int row;
        //GridView行数
        int col;
        //从第几行开始合并
        int count;
        row = 0;
        count = 0;
        for (col = 1; col < this.GridView1.Rows.Count; col++)
        {
            if (GridView1.Rows[col - 1].Cells[iColumns].Text == GridView1.Rows[col].Cells[iColumns].Text)
            {
                row = row + 1;
                GridView1.Rows[col].Cells[iColumns].Visible = false;
                if (col == GridView1.Rows.Count - 1)
                {
                    row = row + 1;
                    GridView1.Rows[count].Cells[iColumns].RowSpan = row;
                    count = 0;
                }
            }
            else
            {
                GridView1.Rows[count].Cells[iColumns].RowSpan = row + 1;
                row = 0;
                count = col;
            }
        }
    }

 

     如果需要合并的列是模板列,就使用下面的方法。

     //ControlID:模板列控件的ID

    private void MergeGridTemplateCell(int iColumns,string ControlID)    {
        int row ; 

        int col ; 
        int count;
        row = 0;
        count = 0;
        for (col = 1; col < this.GridView1.Rows.Count; col++)
        {
            if (((Literal)GridView1.Rows[col - 1].Cells[iColumns].FindControl(ControlID)).Text == ((Literal)GridView1.Rows[col].Cells[iColumns].FindControl(ControlID)).Text)//"litDay"
            {
                row = row + 1;
                GridView1.Rows[col].Cells[iColumns].Visible = false;
                if (col == GridView1.Rows.Count - 1)
                {
                    row = row + 1;
                    GridView1.Rows[count].Cells[iColumns].RowSpan = row;
                    count = 0;
                }
            }
            else
            {
                GridView1.Rows[count].Cells[iColumns].RowSpan = row + 1;
                row = 0;
                count = col;
            }
        }
    }

     调用方法:

     this.MergeGridCell(2);
     this.MergeGridTemplateCell(3, "lblDay");

     合并后的效果:

     

抱歉!评论已关闭.