std9.jp

C# WinForms の DataGridView に行番号を表示する方法

プロパティの変更だけで行番号の表示ができるわけではなく自前で行番号を描画する必要があります。

目次 (4)
  1. 完成形
  2. 実装方法
  3. (1) イベントの登録
  4. (2) 行番号の描画処理

完成形

行番号を表示したい

全体像として、プロパティの変更だけで行番号の表示ができるわけではなく自前で行番号を描画する必要があります。

実装方法

(1) イベントの登録

DataGridView の CellPainting イベントを登録します。

CellPaintingイベントを登録

(2) 行番号の描画処理

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.ColumnIndex < 0 && 0 <= e.RowIndex)
    {
        // セルを描画
        e.Paint(e.ClipBounds, DataGridViewPaintParts.All);

        // 行番号を描画
        TextRenderer.DrawText(
            e.Graphics,
            (e.RowIndex + 1).ToString(),
            e.CellStyle.Font,
            e.CellBounds,
            e.CellStyle.ForeColor,
            TextFormatFlags.Right | TextFormatFlags.VerticalCenter);

        // 描画完了
        e.Handled = true;
    }
}

以上で完了です。おつかれさまでした~