一直想把datagridview做成报表的样式,但是就得合并单元格,但是发现以前的知识没怎么用的上,后来在王少了这么一个源码,如果大家需要的话,直接复制粘贴就可以了,样式挺好看的。
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (dataGridView1.Rows.Count > 0) { if (dataGridView1.Rows[0].Cells[0].Value.ToString().Trim() != string.Empty) { try { for (int i = 0; i < dataGridView1.Rows.Count; i++) { #region MyRegion if (dataGridView1.Columns[i].Index == e.ColumnIndex && e.RowIndex >= 0) { using ( Brush gridBrush = new SolidBrush(dataGridView1.GridColor), backColorBrush = new SolidBrush(e.CellStyle.BackColor)) { using (Pen gridLinePen = new Pen(gridBrush)) { // 擦除原单元格背景 e.Graphics.FillRectangle(backColorBrush, e.CellBounds); if (e.RowIndex != dataGridView1.RowCount - 1) { if (e.Value.ToString() != dataGridView1.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value.ToString()) { e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);//下边缘的线 } } else { 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, //x1,y1,x2,y2 e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1); #region MyRegion if (e.RowIndex == 0) { //绘制第一列的值 if (e.Value != null) { e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, Brushes.Crimson, e.CellBounds.X + (e.CellBounds.Width - e.Graphics.MeasureString(e.Value.ToString().Trim(), e.CellStyle.Font).Width) / 2, e.CellBounds.Y + 2, StringFormat.GenericDefault); } } else { if (e.Value.ToString() != dataGridView1.Rows[e.RowIndex - 1].Cells[e.ColumnIndex].Value.ToString()) { //绘制值 if (string.IsNullOrEmpty(e.Value.ToString().Trim()).Equals(false)) { e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, Brushes.Crimson, e.CellBounds.X + (e.CellBounds.Width - e.Graphics.MeasureString(e.Value.ToString().Trim(), e.CellStyle.Font).Width) / 2, e.CellBounds.Y + 2, StringFormat.GenericDefault); } } } #endregion e.Handled = true; } } } #endregion } } catch { } } } } /// <summary> /// 添加一个表格 /// </summary> public void addDatatable() { DataColumn dc = new DataColumn("ID"); dt.Columns.Add(dc); dc = new DataColumn("name"); dt.Columns.Add(dc); dc = new DataColumn("age"); dt.Columns.Add(dc); dc = new DataColumn("sex"); dt.Columns.Add(dc); dt.Rows.Add(2, "上海", "5000", "7000"); dt.Rows.Add(2, "北京", "3000", "5600"); dt.Rows.Add(3, "纽约", "6000", "8600"); dt.Rows.Add(3, "华盛顿", "8000", "9000"); dt.Rows.Add(4, "伦敦", "7000", "8800"); }