添加新行后合并Winforms中的DataGridView单元格

时间:2018-09-21 08:17:39

标签: c# winforms datagridview merge

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

我有一个用行数据创建的dataGridView,如下所示:

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

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

然后软件将新行添加到dataGridView,表格如下:

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

由于V和数据1相同,我想拥有的东西是该软件将两个单元合并为类似的东西。

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

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

1 个答案:

答案 0 :(得分:1)

首先要显示出来是什么意思,因为在数据库第二行中,其值将为VData 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");

后再调用它

我想提到的是上面的代码只是示例,它有很多不好的东西,但是正如我所说,这只是示例,我不想为您编写代码,因此您有基础并可以对其进行改进