实际效果图

我们新建一个组件BaseDataGridView,继承System.Windows.Forms.DataGridView
重写OnRowPostPaint方法.
一:如果显示行标题我们则绘制
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);}//绘制完毕}