datagridview中的“不可更改的行号"列 [英] Not Changeable Row number column in datagridview

查看:159
本文介绍了datagridview中的“不可更改的行号"列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用仅用于行号的(只读)列扩展dategridview. 当datagridview按其他列内容排序时,行号行的顺序不应更改(例如excel)! 有可能吗?

I want to extend a dategridview with a (read only) column just for row number. The ROW NUMBER row`s order should not change when datagridview sort by other column content (Like excel)! is possible?

推荐答案

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

We can enumerate each row in one of two ways:

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

在添加的列"中显示

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 .

在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将保留原始行的行号(但在处理行删除时将需要其他代码).例如,此降序排序:

Note about the if statement. The condition e.ColumnIndex == 0 will always preserve numeric order through sorting while the condition header.Value == null will preserve row numbers with the original row (but will need additional code when handling row deletion). For example, this descending sort:

  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

这篇关于datagridview中的“不可更改的行号"列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆