有很多种方法,这里介绍三种:

A:

控件的RowStateChanged事件中添加,RowStateChanged事件是在行的状态更改(例如,失去或获得输入焦点)时发生的事件:

1 e.Row.HeaderCell.Value = (e.Row.Index + 1).ToString();//添加行号
2 
3 //e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);

B:

使用控件的RowPostPaint事件,RowPostPaint事件是在绘制 System.Windows.Forms.DataGridViewRow (所有单元格绘制,执行了行绘制之后)发生的事件,不过使用RowPostPaint事件这种方法在数据量很大的时候性能比较差,每次滚动数据都会触发RowPostPaint事件,绘制行号。

(主要利用TextRenderer.DrawText()方法,使用指定的设备上下文、字体、颜色和格式说明在指定界限中绘制指定文本。)

按 Ctrl+C 复制代码
按 Ctrl+C 复制代码

B)2): 

Winform DataGridView控件添加行号
 1         private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
 2         {
 3             var rowIdx = (e.RowIndex + 1).ToString();
 4             var centerFormat = new StringFormat()
 5             {
 6                 Alignment = StringAlignment.Center,
 7                 LineAlignment = StringAlignment.Center,
 8             };
 9             var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, dataGridView1.RowHeadersWidth, e.RowBounds.Height);
10             e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
11         }
Winform DataGridView控件添加行号

相关文章:

  • 2021-11-25
  • 2021-08-26
  • 2021-12-24
  • 2022-12-23
  • 2022-01-22
  • 2022-02-25
猜你喜欢
  • 2021-10-14
  • 2022-02-06
  • 2021-09-11
  • 2022-01-12
相关资源
相似解决方案