Fork me on GitHub

关于datagridview合并单元格一说

      最近在做项目的时候,要求后台查询出来的数据相同的字段合并单元格,这个东西看着简单,百度一下晚上也有很多类似方法,但是有些方法还是有一定BUG的,所以,我在前人的基础上对代码进行了加工,完成了客户想要的效果。这里把代码分享出来!

  第一种,网上有很多博客的代码都是这样的,就是自己手动绘制。但是网上很多代码都是相同的,并且有一个BUG,就是数据很少的时合并单元格的下面的线会画不出来,所以我把我的代码给贴出来。

  

View Code
1 privatevoid dgvAttendance_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
2 {
3 if (e.ColumnIndex ==0&& e.RowIndex !=-1)
4 {
5 using
6 (
7 Brush gridBrush =new SolidBrush(this.dgvAttendance.GridColor),
8 backColorBrush =new SolidBrush(e.CellStyle.BackColor)
9 )
10 {
11 using (Pen gridLinePen =new Pen(gridBrush))
12 {
13 // 清除单元格
14 e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
15
16 // 画 Grid 边线(仅画单元格的底边线和右边线)
17 // 如果下一行和当前行的数据不同,则在当前的单元格画一条底边线
18 if (e.RowIndex < dgvAttendance.Rows.Count -1&&
19 dgvAttendance.Rows[e.RowIndex +1].Cells[e.ColumnIndex].Value.ToString() !=
20 e.Value.ToString())
21 e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
22 e.CellBounds.Bottom -1, e.CellBounds.Right -1,
23 e.CellBounds.Bottom -1);
24 //画最后一条记录的底线
25 if (e.RowIndex == dgvAttendance.Rows.Count -1)
26 e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left +2, e.CellBounds.Bottom -1, e.CellBounds.Right -1, e.CellBounds.Bottom -1);
27 //画右边线
28 e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right -1,
29 e.CellBounds.Top, e.CellBounds.Right -1,
30 e.CellBounds.Bottom);
31
32 // 画(填写)单元格内容,相同的内容的单元格只填写第一个
33 if (e.Value !=null)
34 {
35 if (e.RowIndex >0&&
36 dgvAttendance.Rows[e.RowIndex -1].Cells[e.ColumnIndex].Value.ToString() ==
37 e.Value.ToString())
38 {
39
40 }
41 else
42 {
43 e.Graphics.DrawString((String)e.Value, e.CellStyle.Font,
44 Brushes.Black, e.CellBounds.X +2,
45 e.CellBounds.Y +5, StringFormat.GenericDefault);
46 }
47 }
48 e.Handled =true;
49 }
50 }
51 }
52 }

第二种方法就是自己重写一个datagridview控件,呵呵,我人比较懒,直接在网上下载了一个类似的控件,然后把代码改了一下,实现了效果,呵呵……

效果图如下:

下载请戳

若大家还有别的好的方法,拿出来分享下吧!呵呵……

posted @ 2011-03-03 15:08  马战鹏  阅读(9776)  评论(43编辑  收藏  举报