DevExpress SpreadsheetControl 分组

实现效果:点击单元格,该单元格下方临近的分组收缩或展开。由于DevExpress SpreadsheetControl控件本身的Bug,被点击的单元格上方不能紧邻另外一个分组,否则也会被展开。

原理:利用SpreadsheetCommandId.HideDetail或SpreadsheetCommandId.ShowDetail,展开时必须先选中分组上方单元格或行,收缩时必须选中分组包含的单元格或行。

代码:

        using DevExpress.XtraSpreadsheet.Commands;

        Worksheet worksheet;
        private void Form1_Load(object sender, EventArgs e) {
            worksheet = spreadsheetControl1.ActiveWorksheet;
            worksheet.Rows.Group(2, 4, true);
            worksheet.Rows.Group(17, 20, true);
            worksheet.Rows.Group(27, 30, true);
            worksheet.Cells["A2"].SetValue("Expand");
            worksheet.Cells["A7"].SetValue("Expand");
            worksheet.Cells["A32"].SetValue("AAAAA");//这个必须有,目的配合后面的spreadsheetControl1.ActiveWorksheet.GetDataRange()
        }
        private void spreadsheetControl1_MouseClick(object sender, MouseEventArgs e) {
            Cell cell = spreadsheetControl1.GetCellFromPoint(e.Location);
            if(cell != null) {
                Row currentRow = worksheet.Rows[cell.TopRowIndex];
                if(currentRow.GroupLevel == 0) {
                    int bottomRowIndex = spreadsheetControl1.ActiveWorksheet.GetDataRange().BottomRowIndex;
                    Row childRow = null;
                    for (int i = cell.TopRowIndex + 1; i <= bottomRowIndex; i++)
                    {
                        if (spreadsheetControl1.ActiveWorksheet.Rows[i].GroupLevel != 0)
                        {
                            childRow = spreadsheetControl1.ActiveWorksheet.Rows[i];
                            break;
                        }
                    }
                    if(childRow != null) {

                        if(childRow.Visible) {
                            worksheet.SelectedCell = childRow[0];
                            SpreadsheetCommand command = spreadsheetControl1.CreateCommand(SpreadsheetCommandId.HideDetail);
                            command.Execute();
                            cell.SetValue("Expand");
                            worksheet.SelectedCell = cell;
                        }
                        else {
                            worksheet.SelectedCell = spreadsheetControl1.ActiveWorksheet.Rows[childRow .TopRowIndex- 1][0];
                            SpreadsheetCommand command = spreadsheetControl1.CreateCommand(SpreadsheetCommandId.ShowDetail);
                            command.Execute();
                            cell.SetValue("Collapse");
                        }
                    }

                }
            }
       }




你可能感兴趣的:(DevExpress SpreadsheetControl 分组)