实际效果图
我们新建一个组件BaseDataGridView,继承System.Windows.Forms.DataGridView
重写OnRowPostPaint方法
软谋的.NET全套架构视频,大多视频包含源码,录制时间(初中级是2019~2020高级架构是2020~2021),原价6499,现仅需299元。这个活动周三推出后,受到热捧,仅一个技术群就几十人抢购!最后几天活动,目录和介绍:点击下方超链接查看 需要的加微zls20210502,进技术群的加微mm1552923,备注进群 |
一:如果显示行标题我们则绘制
if (RowHeadersVisible)
二:如果当前行处于选中状态,我们则绘制
if ((e.State & DataGridViewElementStates.Selected) != 0)
先绘制整个行标题的背景颜色
e.Graphics.FillRectangle(new SolidBrush(Color.White), new Rectangle(e.RowBounds.Left, e.RowBounds.Top, RowHeadersWidth, e.RowBounds.Height));
然后绘制色块
e.Graphics.FillRectangle(new SolidBrush(Color.Red), new Rectangle(e.RowBounds.Left, e.RowBounds.Top, 4, e.RowBounds.Height));
如果没有被选中则只绘制背景颜色
e.Graphics.FillRectangle(new SolidBrush(Color.White), new Rectangle(e.RowBounds.Left, e.RowBounds.Top, RowHeadersWidth, e.RowBounds.Height));
三:绘制标题序号
if (e.RowIndex < 0) return;
string sortNo = (e.RowIndex + 1).ToString(); e.Graphics.DrawString(sortNo, RowHeadersDefaultCellStyle.Font, new SolidBrush(RowHeadersDefaultCellStyle.ForeColor), new Rectangle(e.RowBounds.Left + 6, e.RowBounds.Top, RowHeadersWidth, e.RowBounds.Height));
四:绘制单元格的线条
e.Graphics.DrawLine(new Pen(Color.Red), e.RowBounds.Left, e.RowBounds.Bottom - 1, e.RowBounds.Right, e.RowBounds.Bottom - 1);
e.Graphics.DrawLine(new Pen(Color.Red), e.RowBounds.Left + RowHeadersWidth - 1, e.RowBounds.Top, e.RowBounds.Left + RowHeadersWidth - 1, e.RowBounds.Bottom);
完整代码
protected override void OnRowPostPaint(DataGridViewRowPostPaintEventArgs e)
{
base.OnRowPostPaint(e);
//如果显示行号
if (RowHeadersVisible)
{
if ((e.State & DataGridViewElementStates.Selected) != 0)
{
//绘制空白区域
e.Graphics.FillRectangle(new SolidBrush(Color.White), new Rectangle(e.RowBounds.Left, e.RowBounds.Top, RowHeadersWidth, e.RowBounds.Height));
//绘制一个宽度为4的红色块
e.Graphics.FillRectangle(new SolidBrush(Color.Red), new Rectangle(e.RowBounds.Left, e.RowBounds.Top, 4, e.RowBounds.Height));
}
else //如果没有被选中 背景色则为白色
{
e.Graphics.FillRectangle(new SolidBrush(Color.White), new Rectangle(e.RowBounds.Left, e.RowBounds.Top, RowHeadersWidth, e.RowBounds.Height));
}
//绘制行号
if (e.RowIndex < 0) return;
string sortNo = (e.RowIndex + 1).ToString();
e.Graphics.DrawString(sortNo, RowHeadersDefaultCellStyle.Font, new SolidBrush(RowHeadersDefaultCellStyle.ForeColor), new Rectangle(e.RowBounds.Left + 6, e.RowBounds.Top, RowHeadersWidth, e.RowBounds.Height));
//绘制行号线条
e.Graphics.DrawLine(new Pen(Color.Red), e.RowBounds.Left, e.RowBounds.Bottom - 1, e.RowBounds.Right, e.RowBounds.Bottom - 1);
e.Graphics.DrawLine(new Pen(Color.Red), e.RowBounds.Left + RowHeadersWidth - 1, e.RowBounds.Top, e.RowBounds.Left + RowHeadersWidth - 1, e.RowBounds.Bottom);
}
//绘制完毕
}