Windows Forms DataGridView datagridoes not provide the function of merging cells. to merge cells, use Graphics. DrawLine and Graphics. DrawString in the CellPainting event to "Draw ".
The following code merges cells with the same content in the 1st column of the DataGridView 1st: private void dataGridView1_CellPainting (object sender, DataGridViewCellPaintingEventArgs e) {// merges the cells with the same content in the column if (e. columnIndex = 0 & e. rowIndex! =-1) {using (Brush gridBrush = new SolidBrush (this. dataGridView1.GridColor), backColorBrush = new SolidBrush (e. cellStyle. backColor) {using (Pen gridLinePen = new Pen (gridBrush) {// clear cell e. graphics. fillRectangle (backColorBrush, e. cellBounds );
// Draw a Grid edge (only draw the bottom and right lines of cells) // if the data of the next row is different from that of the current row, draw a baseline if (e. rowIndex <dataGridView1.Rows. count-1 & dataGridView1.Rows [e. rowIndex + 1]. cells [e. columnIndex]. value. toString ()! = E. value. toString () e. graphics. drawLine (gridLinePen, e. cellBounds. left, e. cellBounds. bottom-1, e. cellBounds. right-1, e. cellBounds. bottom-1); // draw the right e. graphics. drawLine (gridLinePen, e. cellBounds. right-1, e. cellBounds. top, e. cellBounds. right-1, e. cellBounds. bottom );
// Draw (fill in) the content of the cell. Only the first if (e. Value! = Null) {if (e. rowIndex> 0 & dataGridView1.Rows [e. rowIndex-1]. cells [e. columnIndex]. value. toString () = e. value. toString () {} else {e. graphics. drawString (String) e. value, e. cellStyle. font, Brushes. black, e. cellBounds. X + 2, e. cellBounds. Y + 5, StringFormat. genericDefault) ;}} e. handled = true ;}}}