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;
    }
}

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值