【问题标题】:How to merge DataGridView cells? [duplicate]如何合并 DataGridView 单元格? [复制]
【发布时间】:2016-05-11 09:39:48
【问题描述】:

我在下面的 MySql 数据库中有 datagridview:

我想合并具有相同值的数据行。结果应如下所示:

【问题讨论】:

  • 不幸的是,没有直接的方法可以实现这一点。您必须自己通过覆盖OnPaint 方法来创建这种机制。查看this question。接受的答案有一个相当不错的例子,用于合并 DataGridView 中的单元格。
  • 你的意思是合并单元格?合并数据?请澄清您的问题。
  • @Oscar 合并单元格我的意思是
  • @Nasreddine 好吧,必须重写一些负责渲染控制的方法。不过,你是对的。如果是这种情况,则没有必要专门覆盖 DataGridView 的 OnPaint。我太宽泛了。
  • @Ehsan 第二个 dup 与 DataGridView 或 WinForms 无关。请考虑将其从重复列表中删除。

标签: c# winforms datagridview


【解决方案1】:

此函数可以根据需要合并单元格:

private void MergeCells()
{ 
    HierarchyItem rowItem1 = grid.RowsHierarchy.Items[0];
    HierarchyItem columnItem1 = grid.ColumnsHierarchy.Items[0];

    // create a custom cell style.
    GridCellStyle style = new GridCellStyle();
    style.FillStyle = new FillStyleSolid(Color.FromArgb(255, 0, 175, 240));
    style.Font = new Font(this.Font.FontFamily, 11.0f, FontStyle.Bold);
    style.TextColor = Color.White;
    GridCellStyle orangestyle = new GridCellStyle();
    orangestyle.FillStyle = new FillStyleSolid(Color.FromArgb(255, 254, 122, 1));
    orangestyle.Font = new Font(this.Font.FontFamily, 10.0f, FontStyle.Bold);
    orangestyle.TextColor = Color.White;
    grid.CellsArea.SetCellTextAlignment
    (rowItem1, columnItem1, ContentAlignment.MiddleCenter);
    // set the cell span to 1 row and 5 columns.
    grid.CellsArea.SetCellSpan(rowItem1, columnItem1, 1, 5);
    // set the merged cell value and style.
    grid.CellsArea.SetCellDrawStyle(rowItem1, columnItem1, style);
    // set the cell span to 1 row and 2 columns.
    grid.CellsArea.SetCellSpan(grid.RowsHierarchy.Items[1], columnItem1, 1, 3);
    grid.CellsArea.SetCellDrawStyle
    (grid.RowsHierarchy.Items[1], columnItem1, orangestyle);

    // set the merged cell value.

    // set the cell span to 1 row and 2 columns.
    grid.CellsArea.SetCellSpan
    (grid.RowsHierarchy.Items[1], this.grid.ColumnsHierarchy.Items[3], 1, 2);

    // set the merged cell value.
    grid.CellsArea.SetCellDrawStyle
    (grid.RowsHierarchy.Items[1], this.grid.ColumnsHierarchy.Items[3], orangestyle);
}

【讨论】:

  • 这肯定是在 Windows 窗体 DataGridView 控件上完成的,因为我无法获取 DataGridViewCell 上的 Attributes 属性???
  • 我会试试的。谢谢!
猜你喜欢
  • 2012-04-02
  • 2013-05-22
  • 1970-01-01
  • 1970-01-01
  • 2015-04-21
  • 1970-01-01
  • 2016-04-27
  • 2019-10-29
  • 1970-01-01
相关资源
最近更新 更多