1using System;
2using System.Collections.Generic;
3using System.Text;
4using System.Windows.Forms;
5using System.Drawing;
6
7namespace DataGridView2
8{
9 /// <summary>
10 /// display a datagrid with row numbers
11 /// </summary>
12 class DataGridView2 : DataGridView
13 {
14 /// <summary>
15 /// draw the row number on the header cell, auto adjust the column width
16 /// to fit the row number
17 /// </summary>
18 /// <param name="e"></param>
19 protected override void OnRowPostPaint(DataGridViewRowPostPaintEventArgs e)
20 {
21 base.OnRowPostPaint(e);
22
23 // get the row number in leading zero format,
24 // where the width of the number = the width of the maximum number
25 int RowNumWidth = this.RowCount.ToString().Length;
26 StringBuilder RowNumber = new StringBuilder(RowNumWidth);
27 RowNumber.Append(e.RowIndex + 1);
28 while (RowNumber.Length < RowNumWidth)
29 RowNumber.Insert(0, "0");
30
31 // get the size of the row number string
32 SizeF Sz = e.Graphics.MeasureString(RowNumber.ToString(), this.Font);
33
34 // adjust the width of the column that contains the row header cells
35 if (this.RowHeadersWidth < (int)(Sz.Width + 20))
36 this.RowHeadersWidth = (int)(Sz.Width + 20);
37
38 // draw the row number
39 e.Graphics.DrawString(
40 RowNumber.ToString(),
41 this.Font,
42 SystemBrushes.ControlText,
43 e.RowBounds.Location.X + 15,
44 e.RowBounds.Location.Y + ((e.RowBounds.Height - Sz.Height) / 2));
45 }
46 }
47}
48