I have some data in a grid that currently displays like this:
------------------ |Hd1| Value | ------------------ |A | A1 | ------------------ |A | A2 | ------------------ |A | A3 | ------------------ |A | A4 | ------------------ |B | B1 | ------------------ |B | B2 | ------------------ |B | B3 | ------------------ |B | B4 | ------------------ |B | B5 | ------------------ |C | C1 | ------------------ |C | C2 | ------------------
I want to make it look like this:
|Hd | Value | ------------------ |A | A1 | ---------- | | A2 | ---------- | | A3 | ---------- | | A4 | ------------------ |B | B1 | ---------- | | B2 | ---------- | | B3 | ---------- | | B4 | ---------- | | B5 | ------------------ |C | C1 | ---------- | | C2 | ------------------
Is there any way that I can merge these cells? I have tried in many ways also google but did not find any suitable way. If it is possible showing this data another way without using datagridview but the result is the way I have showed, that will also solve my problem.
The DataGridView control has no related properties or methods to merge cells, but you can accomplish the same using custom painting. You can use DataGridView. CellPainting event or override the Paint method. Plus you will need to override the DataGridView.
Windows Forms DataGridView control has no related properties or methods to merge cells. But you can use Graphics. DrawLine and Graphics. DrawString methods to draw the effect in DataGridView.
You must first find a duplicate values
Need to two methods:
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(); }
in the event, cellpainting:
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; } }
now in cell formatting:
if (e.RowIndex == 0) return; if (IsTheSameCellValue(e.ColumnIndex, e.RowIndex)) { e.Value = ""; e.FormattingApplied = true; }
and in form_load:
dataGridView1.AutoGenerateColumns = false;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With