我想扩展一个带有(只读)列的dategridview,仅用于行号。 当datagridview按其他列内容排序时(如excel),ROW NUMBER行的顺序不应该改变! 有可能吗?
答案 0 :(得分: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;
}
}
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
将保留行号与原始行(但在处理行删除时将需要其他代码)。例如,这种降序排序:
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