Show row number on WinForm DataGridView

I had to work out how to add row numbers to the row header of a WinForm DataGridView. This is something I have done in the past. As the previous code is not accessible to me I had to research how to do it again.
The common approach is to create a handler for the DataGridViewRowPostPaint event. In this method you basically measure the bounding area of the RowHeader and paint the text to the DataGridViewRow.

private void mainGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    var rowHeaderText = (e.RowIndex + 1).ToString();
    var dgv = sender as DataGridView;
    using (SolidBrush brush = new SolidBrush(dgv.RowHeadersDefaultCellStyle.ForeColor))
    {
        var textFormat = new StringFormat()
        {
            Alignment = StringAlignment.Far,
            LineAlignment = StringAlignment.Far
        };

        var bounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, dgv.RowHeadersWidth, e.RowBounds.Height);
        e.Graphics.DrawString(rowHeaderText, this.Font, brush, bounds, textFormat);
    }
}

The code above will work fine but there is one situation where some help is required. If the grid contains a lot of rows the string represention of the row number will wrap. We can fix this by resizing the RowHeader width in the RowPrePaint event by measuring the size of the string and resizing the RowHeader with accordingly.

private void mainGridView_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
    var firstRowIndex = mainGridView.FirstDisplayedCell.RowIndex;
    var lastRowIndex = firstRowIndex + mainGridView.RowCount;
           

    Graphics Graphics = mainGridView.CreateGraphics();
    int measureFirst = (int)(Graphics.MeasureString(firstRowIndex.ToString(), mainGridView.Font).Width);
    int measureLast = (int)(Graphics.MeasureString(lastRowIndex.ToString(), mainGridView.Font).Width);

    int rowHeaderWitdth = System.Math.Max(measureFirst, measureLast);
    mainGridView.RowHeadersWidth = rowHeaderWitdth+15;
}

As of present, this code will work with .Net 2.0 and above with no modification.