[英]Show Row Index in cells of a Column in DataGridView
I need to show an auto increment value in cells of a column in DataGridView
. 我需要在DataGridView
的列的单元格中显示自动增量值。 The type of column is DataGridViewLinkColumn
and the grid should be like this: 列的类型为DataGridViewLinkColumn
,并且网格应如下所示:
| Column X | Column Y |
-----------------------
| 1 | ........ |
| 2 | ........ |
| ........ | ........ |
| n | ........ |
I tried these codes, but it doesn't work: 我尝试了这些代码,但是不起作用:
int i = 1;
foreach (DataGridViewLinkColumn row in dataGridView.Columns)
{
row.Text = i.ToString();
i++;
}
Can anyone help me, please? 有人可以帮我吗?
You can handle CellFormatting
event of your DataGridView
and then provide the value for cell there: 您可以处理DataGridView
CellFormatting
事件,然后在那里提供单元格的值:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex < 0 || e.RowIndex == this.dataGridView1.NewRowIndex)
return;
//Check if the event is fired for your specific column
//I suppose LinkColumn is name of your link column
//You can use e.ColumnIndex == 0 for example, if your link column is first column
if (e.ColumnIndex == this.dataGridView1.Columns["LinkColumn"].Index)
{
e.Value = e.RowIndex + 1;
}
}
It's better to not use a simple for
or foreach
loop because if you sort the grid using another column, the order of numbers in this column will be unordered. 最好不要使用简单的for
或foreach
循环,因为如果使用另一列对网格进行排序,则此列中的数字顺序将是无序的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.