Winform DataGridView控件添加行号

时间:2021-11-13 03:17:12

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

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:

控件的RowStateChanged事件中添加,,RowStateChanged事件是在绘制 System.Windows.Forms.DataGridViewRow 后发生的事件:

1 private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) 2 { 3 //添加行号 4 System.Drawing.Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Y, this.dataGridView1.RowHeadersWidth - 4, this.dataGridView1.ColumnHeadersHeight); 5 TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), this.dataGridView1.RowHeadersDefaultCellStyle.Font, rectangle, this.dataGridView1.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);//”TextFormatFlags.VerticalCenter | TextFormatFlags.Right“中“|”有增加的作用,此处添加了两种文本字符格式样式 6 //this.dataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.FromArgb(192, 192, 255);//行标题单元格BackColor 7 //this.dataGridView1.RowHeadersDefaultCellStyle.BackColor = SystemColors.Control; 8 }

Winform DataGridView控件添加行号