如何在 Winforms 中合并 DataGridView 单元格 [英] How to Merge DataGridView Cell in Winforms

查看:43
本文介绍了如何在 Winforms 中合并 DataGridView 单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在当前显示的网格中有一些数据:

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

有什么办法可以合并这些单元格吗?我也尝试了很多方法,但没有找到任何合适的方法.如果可以在不使用 datagridview 的情况下以另一种方式显示此数据,但结果是我显示的方式,那也将解决我的问题.

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.

推荐答案

必须先找到重复值

需要两种方法:

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

现在是单元格格式:

if (e.RowIndex == 0)
    return;
if (IsTheSameCellValue(e.ColumnIndex, e.RowIndex))
{
    e.Value = "";
    e.FormattingApplied = true;
}

并在 form_load 中:

and in form_load:

dataGridView1.AutoGenerateColumns = false;

这篇关于如何在 Winforms 中合并 DataGridView 单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆