datagridview column index

Viewed 41283

I have a form with a DataGridView widget and I need to get the index of the column with the selected name.

For example, let's say that I have a table with 2 columns: Name, Surname. I need a way to get index of the column name. The problem is that it changes all the time depending on the DataSource but that column always has the same name "Name".

Does anyone know how to solve the problem?

5 Answers

I have found it safer to use the column object's Name property, instead of using the column name as a string, because this allows for more consistent code refactoring in the future.

datagridview1.Columns[column1.Name].Index;

Also, it is important to first make sure the column is not null and, as others have said, that it is contained within the datagridview.

Related