DataGridView的左侧那一列显示行号
选中dataGriView1,然后在属性列表的事件选择RowPostPaint事件,双击后添加事件处理函数,代码如下:
private void dgv_detail_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
//描绘文本的位置
Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
e.RowBounds.Location.Y,
dataGridView1.RowHeadersWidth - 4,//行头宽
e.RowBounds.Height);//宽
//描绘行头文本
TextRenderer.DrawText(e.Graphics,
(e.RowIndex + 1).ToString(),//内容
dataGridView1.RowHeadersDefaultCellStyle.Font,//字体
rectangle,//位置
dataGridView1.RowHeadersDefaultCellStyle.ForeColor,//颜色
TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
}
以上代码原文来自:https://www.cnblogs.com/wanghaibin/articles/1916440.html
如有侵权,请联系删除。
不显示最左边默认的那行:
dataGridView1.RowHeadersVisible = false;
显示左边行号,其它实现代码:
private void dgvReprt_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
using (SolidBrush b = new SolidBrush(dgv.RowHeadersDefaultCellStyle.ForeColor))
{
e.Graphics.DrawString(Convert.ToString(e.RowIndex + 1, System.Globalization.CultureInfo.CurrentUICulture), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 10, e.RowBounds.Location.Y + 4);
}
}