1. 程式人生 > >GridControl 列合併(自定義分組條件)

GridControl 列合併(自定義分組條件)

說明:

    當前方式不提倡,最好還是使用 (1)主從表、或(2)分組。

一、資料來源

DataTable dta = new DataTable();
dta.Columns.Add("A");
dta.Columns.Add("B");
dta.Columns.Add("C");
dta.Columns.Add("D");
for (int m = 1; m <=20; m++)
  dta.Rows.Add($"A{m/5}", $"B", $"C{m/2}",$"D{m}");
grid.DataSource = dta;

二、預設合併

gv.OptionsView.AllowCellMerge = true;

三、根據條件分組合並(根據列A分組合並)

呼叫示例:

FuncGrid.SetMergeCell(gv, "A", new[] { "B", "C" });

四、自定類

        #region 按條件合併
        
        private static string _groupName;
        private static string[] _mergeCols;
        /// <summary>
        /// GridView合併(自定義分組)
        /// </summary>
        /// <param name="gv"></param>
        /// <param name="groupName">分組列(需要合併的列)</param>
        /// <param name="mergeCols">需要合併的列</param>
        public static void SetMergeCell(GridView gv, string groupName, string[] mergeCols)
        {
            gv.OptionsView.AllowCellMerge = true;
            _groupName = groupName;
            _mergeCols = mergeCols;
            gv.CellMerge += Gv_CellMerge;
        }

        private static void Gv_CellMerge(object sender, CellMergeEventArgs e)
        {
            try
            {
                GridView myGv = sender as GridView;
                if (myGv == null) return;
                DataRow dra1 = myGv.GetDataRow(e.RowHandle2 - 1);
                DataRow dra2 = myGv.GetDataRow(e.RowHandle2);
                if (dra1 == null || dra2 == null) return;

                foreach (string str in _mergeCols)
                {
                    if (e.Column.FieldName == str)
                    {
                        bool isOk1 = dra1[_groupName].ToString() == dra2[_groupName].ToString();
                        bool isOk2 = dra1[str].ToString() == dra2[str].ToString();
                        e.Merge = isOk1 && isOk2;
                        e.Handled = true;
                    }
                }
            }
            catch
            {
            }
        }

        #endregion