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

本文关键字:索引 显示 DataGridView 单元格 | 更新日期: 2023-09-27 18:19:28

我需要在DataGridView中的列的单元格中显示一个自动递增值。列的类型是DataGridViewLinkColumn,网格应该是这样的:

| Column X | Column Y |
-----------------------
|    1     | ........ |
|    2     | ........ |
| ........ | ........ |
|    n     | ........ |

我试过这些代码,但不起作用:

int i = 1;
foreach (DataGridViewLinkColumn row in dataGridView.Columns)
{                
    row.Text = i.ToString();
    i++;
}

有人能帮我吗?

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

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

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

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