webform gridview合并单元格

gridview合并单元格

由于项目要求,需要合并某些单元格,因此特意封装了如下帮助类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;

namespace Web
{
    /// <summary>
    /// 合并单元格
    /// </summary>
    public class MergeCellHelper
    {
        /// <summary>
        /// 合并表头
        /// </summary>
        /// <param name="row">当前行</param>
        /// <param name="startColumn">开始列</param>
        /// <param name="endColumn">结束列</param>
        public static void MergeHeader(GridViewRow row, int startColumn, int endColumn)
        {
            for (int i = startColumn; i <= endColumn; i++)
            {
                if (i == startColumn)
                {
                    row.Cells[startColumn].ColumnSpan = endColumn - startColumn + 1;
                }
                else
                {
                    row.Cells[i].Visible = false;
                }
            }
        }

        /// <summary>
        /// 合并指定列的行
        /// </summary>
        /// <param name="gv">gridview</param>
        /// <param name="columns">指定的列:可以多列</param>
        public static void MergeRow(GridView gv, params int[] columns)
        {
            for (int i = 0; i < columns.Length; i++)
            {
                var currentColumn = columns[i];
                for (int j = 0; j < gv.Rows.Count; j++)
                {
                    var currentRow = gv.Rows[j];
                    if (j < gv.Rows.Count - 1)
                    {
                        var nextRow = gv.Rows[j + 1];
                        if (currentRow.Cells[0].Text == nextRow.Cells[0].Text)
                        {
                            if (currentRow.Cells[currentColumn].Text == nextRow.Cells[currentColumn].Text)
                            {
                                currentRow.Cells[currentColumn].RowSpan = currentRow.Cells[currentColumn].RowSpan < 2 ? 2 : currentRow.Cells[currentColumn].RowSpan + 1;
                                nextRow.Cells[currentColumn].Visible = false;
                            }
                        }
                    }
                }
            }
        }
    }
}

 

上一篇:Leetcode-1030 Matrix Cells in Distance Order(距离顺序排列矩阵单元格)


下一篇:EXCEL的VBA(宏)编程