【问题标题】:Not Changeable Row number column in datagridviewdatagridview中不可更改的行号列
【发布时间】:2015-06-04 22:30:03
【问题描述】:

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

【问题讨论】:

  • 你能展示一些代码来展示你到目前为止所做的尝试吗?

标签: c# sorting datagridview row


【解决方案1】:

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

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

在添加的列中显示

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;
  }
}

感谢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

【讨论】:

    猜你喜欢
    • 2023-03-17
    • 2023-03-14
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    相关资源
    最近更新 更多