本文主要是介绍datagridview合并单元格,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
private void dataGridView5_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
DataGridView dataGridView = this.dataGridView5;
// 假设你的DataGridView有至少三行三列
if (e.RowIndex == 2 && e.ColumnIndex == 2) //合并第三行最后两列
{
// 确定合并区域的起始单元格位置
Rectangle rect = new Rectangle(
e.CellBounds.Left - dataGridView.Columns[e.ColumnIndex - 1].Width,
e.CellBounds.Top,
e.CellBounds.Width + dataGridView.Columns[e.ColumnIndex - 1].Width,
e.CellBounds.Height);
// 使用双重缓冲绘制
using (Graphics g = dataGridView.CreateGraphics())
{
// 保存 SmoothingMode 并设置为 AntiAlias
SmoothingMode smoothingMode = g.SmoothingMode;
g.SmoothingMode = SmoothingMode.AntiAlias;
// 填充合并后的单元格背景色
using (Brush backColorBrush = new SolidBrush(e.CellStyle.BackColor))
//using (Brush backColorBrush = new SolidBrush(Color.Red))
{
g.FillRectangle(backColorBrush, rect);
}
// 画合并单元格边界线
using (Pen gridLinePen = new Pen(dataGridView.GridColor))
{
绘制上边线
//g.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Top - 1, rect.Right - 1, e.CellBounds.Top - 1);
绘制左边线
g.DrawLine(gridLinePen, e.CellBounds.Left - 1, e.CellBounds.Top, e.CellBounds.Left - 1, rect.Bottom - 1);
绘制右边线
//g.DrawLine(gridLinePen, rect.Right, e.CellBounds.Top, rect.Right, rect.Bottom - 1);
绘制下边线
//g.DrawLine(gridLinePen, e.CellBounds.Left, rect.Bottom, rect.Right - 1, rect.Bottom);
}
// 绘制文本
StringFormat format = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
g.DrawString(e.Value.ToString(), e.CellStyle.Font, new SolidBrush(e.CellStyle.ForeColor), rect, format);
// 恢复 SmoothingMode
g.SmoothingMode = smoothingMode;
}
// 取消默认的单元格绘制
e.Handled = true;
}
}
这篇关于datagridview合并单元格的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!