datagridview中的不可更改的行号列

我想扩展一个dategridview与一个(只读)列只为行号。 当datagridview按其他列内容排序时(如excel),ROW NUMBER行的顺序不应该改变! 有可能吗?

我们可以用以下两种方式之一枚举每一行:

  • 添加新列。
  • 在行标题内。

显示添加的列

private void AddIndexCol() { DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn(); col.Name = "Index"; col.HeaderText = "Index"; col.ReadOnly = true; col.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; DataGridViewTextBoxCell cell = new DataGridViewTextBoxCell(); cell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; col.CellTemplate = cell; this.dataGridView1.Columns.Insert(0, col); } private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.ColumnIndex == 0) { e.Value = String.Format("{0}", e.RowIndex + 1); e.FormattingApplied = true; } } 

CellFormatting ASh的CellFormatting代码。


在RowHeader中显示

 public Form1() { InitializeComponent(); DataGridViewCellStyle style = new DataGridViewCellStyle(); style.Alignment = DataGridViewContentAlignment.MiddleCenter; this.dataGridView1.RowHeadersDefaultCellStyle = style; this.dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders; } private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { DataGridViewRowHeaderCell header = this.dataGridView1.Rows[e.RowIndex].HeaderCell; if (e.ColumnIndex == 0) // (header.Value == null) { header.Value = String.Format("{0}", e.RowIndex + 1); } } 

关于if语句的注释。 条件e.ColumnIndex == 0将始终通过排序保留数字顺序,而条件header.Value == null将保留行号与原始行(但在处理行删除时将需要其他代码)。 例如,这种降序排序:

  Col == 0 Header == null 1 a => 1 c 1 a => 3 c 2 b 2 b 2 b 2 b 3 c 3 a 3 c 1 a