首页 > 解决方案 > 添加新行后在 Winforms 中合并 DataGridView 单元格

问题描述

我正在 Visual Studio 2017 中创建一个 WinForms 应用程序,

我有一个使用如下行数据创建的 dataGridView:

-----------------------------------------------------------
| V |      Data 1      | Data 1 Quantity | Data 1 Details |
-----------------------------------------------------------

创建此数据后,用户将一些数据输入文本框并提交。

然后软件在dataGridView中新增一行,Table变成如下:

---------------------------------------------------------------
| V |      Data 1      | Data 1 Quantity   | Data 1 Details   |
---------------------------------------------------------------
| V |      Data 1      | Data 1.A Quantity | Data 1.A Details |
---------------------------------------------------------------

因为 V 和 Data 1 是相同的,所以我想拥有什么,软件将两个单元格合并成这样的东西。

-----------------------------------------------------------------
| V   |      Data 1      | Data 1 Quantity   | Data 1 Details   |
                         ---------------------------------------- 
|     |                    Data 1.A Quantity | Data 1.A Details |
-----------------------------------------------------------------

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

标签: c#winformsdatagridviewmerge

解决方案


首先,像这样显示有什么意义,因为在数据库中第二行将具有Vand的值Data 1

你可以做的是用户点击添加行,它检查数据库是否在某些单元格中具有相同的参数(在你的情况下是第一个和第二个),如果是,则不添加新行但更改当前和在其他单元格中添加新值除了旧的。

如果您这样做,那么您dataGridView将像一行一样显示它

-----------------------------------------------------------------
| V   |      Data 1      | Data 1 Quantity   | Data 1 Details   | //when editing existing cell value add new line so it displays like this
|     |                  | Data 1.A Quantity | Data 1.A Details |
-----------------------------------------------------------------

你可以做的另外两件事是:

  • 创建从类继承的自定义控件,DataGridView并在其中创建函数,该函数将自动合并具有某些条件的单元格并根据您的喜好显示它(高级级别)
  • 为此创建扩展方法DataGridView将在某些条件下删除某些单元格的数据

第二种解决方案的示例如下:

public static void EmptyOnDuplicateData(this DataGridView dgv, string columnToEmpty)
{
    List<string> ExistingData = new List<string>(); //I would do this with T and instead of passing string i would pass DataGridViewColumn so i could get type and other things but that is on you and i am just writing example

    foreach(DataGridViewRow row in dgv.Rows)
    {
        if(ExistingData.Contains(row.Cells[columnToEmpty].Value)) //Data from this cell already existed before this cell
        {
            row.Cells[columnToEmpty].Value == ""; //We clear that from that cell
        }
        else // Data from this cell doesn't exist anywhere before
        {
            ExistingData.Add(row.Cells[columnToEmpty].Value);
        }
    }
}

你只是在填充你DataGridView的之后调用它yourDgv.EmptyOnDuplicateData("SomeColumn");

我想提一下,上面的代码只是示例,它有很多不好的东西,但正如我所说,这只是示例,我不想为你编写代码,所以你有基础并只是改进它。


推荐阅读