【WinForm】DataGridView重绘,选择行添加边框

为DataGridView的RowPostPaint绑定事件RowPostPaint += DataGridView_RowPostPaint

private void ZyDataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    if (Rows[e.RowIndex].Selected)
    {
        //绘制选中行边框
        using (Pen pen = new Pen(Color.FromArgb(137, 91, 163)))
        {
            int penWidth = 1;
            pen.Width = penWidth;

            int x = e.RowBounds.Left + (penWidth / 2) + 1;
            int y = e.RowBounds.Top + (penWidth / 2);
            int width = e.RowBounds.Width - penWidth - 3;
            int height = e.RowBounds.Height - penWidth;
            e.Graphics.DrawRectangle(pen, x, y, width, height);
        }
    }
}

效果:

 

如果单元格之间需要分割线,可以在单元格之间绘制直线

private void ZyDataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    if (Rows[e.RowIndex].Selected)
    {
        //绘制选中行边框
        using (Pen pen = new Pen(Color.FromArgb(137, 91, 163)))
        {
            int penWidth = 1;
            pen.Width = penWidth;

            int x = e.RowBounds.Left + (penWidth / 2) + 1;
            int y = e.RowBounds.Top + (penWidth / 2);
            int width = e.RowBounds.Width - penWidth - 3;
            int height = e.RowBounds.Height - penWidth;
            e.Graphics.DrawRectangle(pen, x, y, width, height);

            //绘制单元格之间的分割线
            using (Pen pen1 = new Pen(Color.White))
            {
                int cellWidth = 0;
                var cells = Rows[e.RowIndex].Cells;

                for (int i = 0; i < cells.Count - 1; i++)
                {
                    //已隐藏的列不绘制
                    if (cells[i].Visible == false)
                        continue;

                    cellWidth += cells[i].Size.Width;
                    int cellX = x + cellWidth - 1;
                    e.Graphics.DrawLine(pen1, new Point(cellX, y), new Point(cellX, y + height));
                }
            }
        }
    }
}

效果:

 

参考:

https://www.orcode.com/question/1100404_k11fc0.html

相关推荐
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页