[英]Not Changeable Row number column in datagridview
I want to extend a dategridview with a (read only) column just for row number. 我想使用仅用于行号的(只读)列扩展dategridview。 The ROW NUMBER row`s order should not change when datagridview sort by other column content (Like excel)! 当datagridview按其他列内容排序时,ROW NUMBER行的顺序不应更改(例如excel)! is possible? 有可能吗
We can enumerate each row in one of two ways: 我们可以用以下两种方法之一枚举每一行:
Displaying in Added Column 在添加的列中显示
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;
}
}
Credit to ASh for the CellFormatting
code. CellFormatting
ASh的CellFormatting
代码。
Displaying in RowHeader 在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);
}
}
Note about the if
statement. 注意有关if
语句。 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). 条件e.ColumnIndex == 0
将始终通过排序保留数字顺序,而条件header.Value == null
将保留原始行的行号(但在处理行删除时将需要其他代码)。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.