1、首先为DataGridView添加一个RowPostPaint事件。
2、在事件代码中把下面的代码贴上:
private
void
dataGridView1_RowPostPaint(
object
sender, DataGridViewRowPostPaintEventArgs e)
{
try
{
// 添加行号
SolidBrush v_SolidBrush = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor);
int v_LineNo = 0 ;
v_LineNo = e.RowIndex + 1 ;
string v_Line = v_LineNo.ToString();
e.Graphics.DrawString(v_Line, e.InheritedRowStyle.Font, v_SolidBrush, e.RowBounds.Location.X + 15 , e.RowBounds.Location.Y + 5 );
}
catch (Exception ex)
{
MessageBox.Show( " 添加行号时发生错误,错误信息: " + ex.Message, " 操作失败 " );
}
}
{
try
{
// 添加行号
SolidBrush v_SolidBrush = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor);
int v_LineNo = 0 ;
v_LineNo = e.RowIndex + 1 ;
string v_Line = v_LineNo.ToString();
e.Graphics.DrawString(v_Line, e.InheritedRowStyle.Font, v_SolidBrush, e.RowBounds.Location.X + 15 , e.RowBounds.Location.Y + 5 );
}
catch (Exception ex)
{
MessageBox.Show( " 添加行号时发生错误,错误信息: " + ex.Message, " 操作失败 " );
}
}