1

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?

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
Manraj
  • 496
  • 2
  • 15

1 Answers1

1

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.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398