How to Merge DataGridView Cell in Winforms

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;

Image of DGV_Merge

Leave a Comment