WinForms DataGridView Cell Merge
Question:
In DataGridView, data is arranged in a grid format, containing rows and columns. Each row and column intersection is represented by a cell. In this example, the data is displayed in a format such that duplicate values in the first column (Hd1) are not merged, resulting in multiple rows for the same value.
Requirements:
The goal is to merge cells with duplicate values in the first column (Hd1) to improve visuals and consolidate data efficiently.
Solution:
To merge cells in DataGridView, you can follow these steps:
Find duplicate values:
IsTheSameCellValue
that compares the values of two adjacent cells in the first column. If the values are the same, true
is returned, otherwise false
is returned. <code class="language-csharp">bool IsTheSameCellValue(int column, int row) { DataGridViewCell cell1 = dataGridView1[column, row]; DataGridViewCell cell2 = dataGridView1[column, row - 1]; if (cell1.Value == null || cell2.Value == null) { return false; } return cell1.Value.ToString() == cell2.Value.ToString(); }</code>
Cell drawing:
CellPainting
event handler and modify the cell's AdvancedBorderStyle
property: <code class="language-csharp">private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { e.AdvancedBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.None; if (e.RowIndex < 1 || e.ColumnIndex < 0) return; if (IsTheSameCellValue(e.ColumnIndex, e.RowIndex)) { e.AdvancedBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.None; } else { e.AdvancedBorderStyle.Top = dataGridView1.AdvancedCellBorderStyle.Top; } }</code>
Cell formatting:
CellFormatting
event handler to set the value to an empty string if the cell is a duplicate: <code class="language-csharp">if (e.RowIndex == 0) return; if (IsTheSameCellValue(e.ColumnIndex, e.RowIndex)) { e.Value = ""; e.FormattingApplied = true; }</code>
Other settings:
dataGridView1.AutoGenerateColumns
to false
in the form load event to prevent columns from being automatically generated. <code class="language-csharp">dataGridView1.AutoGenerateColumns = false;</code>
Result:
Performing these steps will merge cells with duplicate values in the first column of the DataGridView, making the data display more compact and organized.
The above is the detailed content of How to Merge Duplicate Cells in a WinForms DataGridView's First Column?. For more information, please follow other related articles on the PHP Chinese website!