步骤一:
确认DataGridView控件的RowHeadersVisible属性为true;(设置第一列/列头不隐藏)
步骤二:
编写RowPostPaint事件方法
private void dgv_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
e.RowBounds.Location.Y,
dgv_data.RowHeadersWidth - 4,
e.RowBounds.Height);
TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
dgv_data.RowHeadersDefaultCellStyle.Font,
rectangle,
dgv_data.RowHeadersDefaultCellStyle.ForeColor,
TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
}
附:
Rectangle(int x, int y, int width, int height);该方法是用指定的位置和大小初始化 System.Drawing.Rectangle 类的新实例。
参数说明: x: 矩形左上角的 x 坐标。 y: 矩形左上角的 y 坐标。 width: 矩形的宽度。 height: 矩形的高度。
TextRenderer.DrawText(IDeviceContext dc, string text, Font font, Rectangle bounds, Color foreColor, TextFormatFlags flags);该方法用于绘制指定的文本,使用指定的设备上下文、 字体、 颜色和格式设置的说明指定的边界内。
参数说明: dc: 在其中绘制文本的设备上下文。 text: 要绘制的文本。 font: System.Drawing.Font 将应用于所绘制文本。 bounds: System.Drawing.Rectangle 表示文本的边界。 foreColor: System.Drawing.Color 将应用于所绘制文本。 flags: System.Windows.Forms.TextFormatFlags 值的按位组合。
步骤三:
在Designer文件中为DataGridView控件绑定RowPostPaint事件
this.dgv_data.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.dgv_RowPostPaint);
效果图: