Search code examples
c#winformsdatagridviewdatagridviewcolumndatagridviewlinkcolumn

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. The type of column is DataGridViewLinkColumn and the grid should be like this:

| 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?


Solution

  • You can handle CellFormatting event of your DataGridView and then provide the value for cell there:

    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.