我是靠谱客的博主 虚幻草丛,这篇文章主要介绍DataGridView合并单元格(横向合并),现在分享给大家,希望可以做个参考。

整理来自于https://blog.csdn.net/huangwenhua5000/article/details/8949638

这里仅进行横向的单元格合并,没有进行纵向的单元格的合并.

合并后的单元格没有点击效果,不过还算理想。代码如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
private void Form1_Load(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Columns.Add("A"); dt.Columns.Add("B"); dt.Columns.Add("C"); dt.Columns.Add("D"); dt.Rows.Add(new object[] { "A1", "B1", "C1", "D1" }); dt.Rows.Add(new object[] { "A2", "B2", "C2", "D2" }); dt.Rows.Add(new object[] { "A3", "B3", "C3", "D3" }); this.dataGridView1.DataSource = dt; } private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.RowIndex < 0 || e.RowIndex >= this.dataGridView1.Rows.Count - 1 || e.ColumnIndex == -1) { return; } // 下面合并单元格第3行第2列(B3)与单元格第3行第3列(C3). if (e.ColumnIndex == 1 && this.dataGridView1[e.RowIndex, e.ColumnIndex + 1].Value.ToString() == "C3") { e.Handled = true; } if (e.ColumnIndex == 2 && e.Value.ToString() == "C3") { //背景颜色 SolidBrush backBrush = new SolidBrush(e.CellStyle.BackColor); if (this.dataGridView1.Rows[e.RowIndex].Selected) { backBrush.Color = e.CellStyle.SelectionBackColor; } //画矩形框 DataGridViewCell preCell = this.dataGridView1[e.ColumnIndex - 1, e.RowIndex]; Rectangle re = new Rectangle(e.CellBounds.Left - this.dataGridView1.Columns[e.ColumnIndex - 1].Width , e.CellBounds.Top, e.CellBounds.Width + this.dataGridView1.Columns[e.ColumnIndex - 1].Width , e.CellBounds.Height); e.Graphics.FillRectangle(backBrush, re); //画边框 Pen pen = new Pen(this.dataGridView1.BackgroundColor, 1); pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; //底边框 e.Graphics.DrawLine(pen, re.X, re.Y + re.Height - 1, re.X + re.Width, re.Y + re.Height - 1); //右边框 e.Graphics.DrawLine(pen, re.X + re.Width - 1, re.Y, re.X + re.Width - 1, re.Y + re.Height); //在矩形框内写入文本 SizeF strSize = e.Graphics.MeasureString(e.Value.ToString(), this.dataGridView1.Font); e.Graphics.DrawString(e.Value.ToString(), this.dataGridView1.Font, Brushes.Black, re.X + (re.Width - strSize.Width) / 2, re.Y + (re.Height - strSize.Height) / 2); e.Handled = true; } }

其他:如果需要深入研究,可参考链接https://blog.csdn.net/qq_31510271/article/details/80094792中的RowMergeView控件,

该控件支持横向与纵向的单元格合并,不过测试中有些小问题,在拖动改变行高时会出现重影,选择含有合并单元格的行时背景色无变化.

最后

以上就是虚幻草丛最近收集整理的关于DataGridView合并单元格(横向合并)的全部内容,更多相关DataGridView合并单元格(横向合并)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(84)

评论列表共有 0 条评论

立即
投稿
返回
顶部