Home >Backend Development >C++ >How to Merge DataGridView Cells in WinForms?

How to Merge DataGridView Cells in WinForms?

Barbara Streisand
Barbara StreisandOriginal
2025-01-12 15:28:43184browse

How to Merge DataGridView Cells in WinForms?

WinForms DataGridView Cell Merging: Complete Guide

The key to merging cells in WinForms's DataGridView is to find and handle duplicate values. Here are step-by-step instructions:

Find duplicate values

Define a helper method to compare cell values ​​for equality:

<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>

CellPainting

In the CellPainting event of DataGridView, adjust the border style of the merged cells:

<code class="language-csharp">private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    e.AdvancedBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.None;
    if (e.RowIndex < 0 || e.ColumnIndex < 0)
        return;
    if (IsTheSameCellValue(e.ColumnIndex, e.RowIndex))
    {
        e.AdvancedBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.None;
    }
}</code>

Cell formatting event (CellFormatting)

In the CellFormatting event, handle the formatting of merged cells:

<code class="language-csharp">private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.RowIndex == 0)
        return;
    if (IsTheSameCellValue(e.ColumnIndex, e.RowIndex))
    {
        e.Value = "";
        e.FormattingApplied = true;
    }
}</code>

Form Loading

Disable automatic column generation:

<code class="language-csharp">private void Form1_Load(object sender, EventArgs e)
{
    dataGridView1.AutoGenerateColumns = false;
}</code>

Through the above steps, you can merge cells in the DataGridView to achieve the desired data presentation effect.

The above is the detailed content of How to Merge DataGridView Cells in WinForms?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn