C# 在DataGridView中以列的单元格显示行索引

C# 在DataGridView中以列的单元格显示行索引,c#,winforms,datagridview,datagridviewcolumn,datagridviewlinkcolumn,C#,Winforms,Datagridview,Datagridviewcolumn,Datagridviewlinkcolumn,我需要在DataGridView中的列单元格中显示一个自动递增值。列的类型为DataGridViewLinkColumn,网格应如下所示: | Column X | Column Y | ----------------------- | 1 | ........ | | 2 | ........ | | ........ | ........ | | n | ........ | 我试过这些代码,但不起作用: int i = 1; foreach (

我需要在
DataGridView
中的列单元格中显示一个自动递增值。列的类型为
DataGridViewLinkColumn
,网格应如下所示:

| Column X | Column Y |
-----------------------
|    1     | ........ |
|    2     | ........ |
| ........ | ........ |
|    n     | ........ |
我试过这些代码,但不起作用:

int i = 1;
foreach (DataGridViewLinkColumn row in dataGridView.Columns)
{                
    row.Text = i.ToString();
    i++;
}
有人能帮我吗?

您可以处理您的
DataGridView
的事件,然后为那里的单元格提供值:

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;
    }
}
private void dataGridView1\u单元格格式(对象发送方,DataGridViewCellFormattingEventArgs e)
{
如果(e.RowIndex<0 | | e.RowIndex==this.dataGridView1.NewRowIndex)
返回;
//检查是否为特定列触发事件
//我想LinkColumn是链接列的名称
//例如,如果链接列是第一列,则可以使用e.ColumnIndex==0
if(e.ColumnIndex==this.dataGridView1.Columns[“LinkColumn”].Index)
{
e、 值=e.RowIndex+1;
}
}

最好不要使用简单的
for
foreach
循环,因为如果使用另一列对网格进行排序,此列中的数字顺序将是无序的。

亲爱的Rock。感谢您的帮助