如果DataGridView控件能顯示行號(hào),對(duì)我們尋找數(shù)據(jù)就非常方便,但DataGridView默認(rèn)的屬性中,不可設(shè)置顯示行號(hào)。本文在DataGridView的RowPostPaint事件中進(jìn)行繪制,實(shí)現(xiàn)了這個(gè)功能,其效果如下:

為了表示行號(hào),我們可以在DataGridView的RowPostPaint事件中進(jìn)行繪制。RowPostPaint事件,具體可以參照MSDN。
下面是實(shí)現(xiàn)代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
namespace DrawRowIndex
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Dock = DockStyle.Fill;
dataGridView1.DataSource = ImageCodecInfo.GetImageDecoders();
}
private void dataGridView1_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);
}
}
}