using System;
using System.Drawing;
using System.Windows.Forms;
namespace 合并DataGridView单元格
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form_Load);
this.dataGridView1.CellPainting+=new DataGridViewCellPaintingEventHandler(dataGridView1_CellPainting);
}
private void Form_Load(object sender, EventArgs e)
{
int index = dataGridView1.Rows.Add();
DataGridViewRow dr = dataGridView1.Rows[index];
dr.Cells["工作编号"].Value = "0001";
dr.Cells["项目名称"].Value = "后台开发";
dr.Cells["小组成员"].Value = "张三";
index = dataGridView1.Rows.Add();
dr = dataGridView1.Rows[index];
dr.Cells["工作编号"].Value = "0002";
dr.Cells["项目名称"].Value = "后台开发";
dr.Cells["小组成员"].Value = "钱五";
index = dataGridView1.Rows.Add();
dr = dataGridView1.Rows[index];
dr.Cells["工作编号"].Value = "0003";
dr.Cells["项目名称"].Value = "中台台开发";
dr.Cells["小组成员"].Value = "李四";
index = dataGridView1.Rows.Add();
dr = dataGridView1.Rows[index];
dr.Cells["工作编号"].Value = "0005";
dr.Cells["项目名称"].Value = "中台台开发";
dr.Cells["小组成员"].Value = "王五";
index = dataGridView1.Rows.Add();
dr = dataGridView1.Rows[index];
dr.Cells["工作编号"].Value = "0006";
dr.Cells["项目名称"].Value = "中台台开发";
dr.Cells["小组成员"].Value = "赵六";
}
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex > -1)
{
if (e.ColumnIndex == 1)
{
Brush datagridBrush = new SolidBrush(dataGridView1.GridColor);//定义一个填充图形内部对象的实例
SolidBrush groupLineBrush = new SolidBrush(e.CellStyle.BackColor);//定义一个单色画笔的实例
using (Pen datagridLinePen = new Pen(datagridBrush))//使用绘制直线或曲线的画笔
{
e.Graphics.FillRectangle(groupLineBrush, e.CellBounds);//清除单元格
if (e.RowIndex < dataGridView1.Rows.Count - 1 && dataGridView1.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value != null
&& dataGridView1.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value.ToString() != e.Value.ToString())
{
//画底边线
e.Graphics.DrawLine(datagridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right, e.CellBounds.Bottom - 1);
//画右边线
e.Graphics.DrawLine(datagridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);
}
else
{
//画右边线
e.Graphics.DrawLine(datagridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);
}
if (e.RowIndex == dataGridView1.Rows.Count - 1)//最后一行只画底边线
{
e.Graphics.DrawLine(datagridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right, e.CellBounds.Bottom - 1);
}
if (e.Value != null)//填写单元格内容,相同内容只填写一个
{
if(!(e.RowIndex>0 && dataGridView1.Rows[e.RowIndex-1].Cells[e.ColumnIndex].Value.ToString()==e.Value.ToString()))
{
//绘制单元格的内容
e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, Brushes.Black, e.CellBounds.X + 2, e.CellBounds.Y + 5, StringFormat.GenericDefault);
}
}
e.Handled = true;//指示处理程序已经完成
}
}
}
}
}
}
DataGridView合并单元格
最新推荐文章于 2024-05-14 15:06:39 发布