2

I have datagridview from MySql database below:

MyDataGridview

I want to combine the data rows that have the same value. the result should look like the following:

MyDataGridviewResult

vivienne
  • 41
  • 2
  • 6
  • 1
    Unfortunately, there's no direct way to achieve that. You'll have to create such mechanism by yourself by overriding `OnPaint` method. Check out [this question](http://stackoverflow.com/questions/2063951/merge-cells-in-datagridview). Accepted answer has a pretty decent example for merging cells in DataGridView. – Bartłomiej Zieliński May 11 '16 at 09:44
  • You mean merge cells? Merge data? Please, clarify your question. – Oscar May 11 '16 at 09:45
  • @Oscar Merge cells i mean – vivienne May 11 '16 at 09:46
  • 1
    @Nasreddine Well, some method responsible for rendering control has to be overridden. You're right, though. It's not necessary to override specifically DataGridView's `OnPaint`, if that's the case. I was too broad. – Bartłomiej Zieliński May 11 '16 at 09:54
  • @Ehsan The second dup is not related to DataGridView or WinForms. Please consider removing it from the duplicates list. – 41686d6564 stands w. Palestine Jun 26 '21 at 08:23
  • @vivienne, how did you make it work? please provide reference to achieve same . – Darshana Nov 12 '21 at 07:35

1 Answers1

-3

This function merge the cells as you want:

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);
}
Saadi
  • 2,211
  • 4
  • 21
  • 50