Question:
Merge cells in a DataGridView for consolidated data display without duplicate rows. The goal is to convert a grid with header values that are repeated across rows into a grid where the header values span merged cells representing the repeated rows.
Solution:
This can be achieved by combining custom cell formatting and paint event handling.
Find duplicate cell values:
First, define a method to determine whether the current cell has the same value as the cell above it:
<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>
Custom cell drawing:
In the DataGridView's cell draw event, remove the borders of cells with duplicate values:
<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>
Customized cell format:
In cell format events, hide duplicate row values:
<code class="language-csharp">if (e.RowIndex == 0) return; if (IsTheSameCellValue(e.ColumnIndex, e.RowIndex)) { e.Value = ""; e.FormattingApplied = true; }</code>
Other settings:
Disable automatic generation of columns to prevent the creation of unwanted columns:
<code class="language-csharp">dataGridView1.AutoGenerateColumns = false;</code>
Result:
By implementing the above steps, the DataGridView will display data with merged cells, eliminate duplicate header values and present a consolidated view.
The above is the detailed content of How to Merge DataGridView Cells in WinForms to Consolidate Data with Duplicate Header Values?. For more information, please follow other related articles on the PHP Chinese website!