private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.RowIndex >= 0 && e.ColumnIndex >= 0 && e.Value.ToString() != string.Empty) { //if (!string.IsNullOrEmpty(this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()) && this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null) //{ #region int UpRows = 0;//上面相同的行數 int DownRows = 0;//下面相同的行數 int count = 0;//總行數 int cellwidth = e.CellBounds.Width;//列寬 //獲取下面的行數 for (int i = e.RowIndex; i < this.dataGridView1.Rows.Count; i++) { if (this.dataGridView1.Rows[i].Cells[e.ColumnIndex].Value.ToString().Equals(e.Value.ToString())) { DownRows++; } else { break; } } //獲取上面的行數 for (int i = e.RowIndex; i >= 0; i--) { if (this.dataGridView1.Rows[i].Cells[e.ColumnIndex].Value.ToString().Equals(e.Value.ToString())) { UpRows++; } else { break; } } count = UpRows + DownRows - 1;//總行數 //if (count < 2) //{ return; } using (Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor), backColorBrush = new SolidBrush(e.CellStyle.BackColor)) { using (Pen gridLinePen = new Pen(gridBrush)) { //this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = this.dataGridView1.Rows[e.RowIndex - 1].Cells[e.ColumnIndex].Value; //this.dataGridView1.Rows[e.RowIndex - 1].Cells[e.ColumnIndex].Value = DBNull.Value; //清除單元格 e.Graphics.FillRectangle(backColorBrush, e.CellBounds); if (e.Value != null) { int cellheight = e.CellBounds.Height; SizeF size = e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font); //if (e.RowIndex > 0 && this.dataGridView1.Rows[e.RowIndex - 1].Cells[e.ColumnIndex].Value.ToString() == e.Value.ToString()) //{ //} //else //{ e.Graphics.DrawString((e.Value).ToString(), e.CellStyle.Font, Brushes.Black, e.CellBounds.X + (cellwidth - size.Width) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - size.Height) / 2, StringFormat.GenericDefault); //} } //如果下一行數據不等於當前行數據,則畫當前單元格底邊線 if (e.RowIndex < this.dataGridView1.Rows.Count - 1 && this.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); } if (e.RowIndex == this.dataGridView1.Rows.Count - 1) { e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left + 2, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1); count = 0; } //畫grid右邊線 //e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1); e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom); e.Handled = true; } } #endregion //} } }
最近整理自己寫過的代碼,發現datagridview行合並代碼,已忘記是摘抄的網上的資料還是自己寫的了,故此處無法寫明參考自何處,如有哪位網友發現來源,麻煩請告知。在下還是很支持正版的。(整理進自己的博客里,方便查看閱讀。O(∩_∩)O~~)