Anoushka Seechurn
Anoushka Seechurn

Reputation: 2256

getting index of a column having a given column header c#

guys i am trying to get the index of a column with a specific column header. Till now i got to

int index_of = grid_statement.Columns[the_name].Index;

But it throws a NullReference exception.

Is there any other ways to get that index ? (the_name is a variable having the column header)

Upvotes: 2

Views: 2962

Answers (3)

Coderz
Coderz

Reputation: 245

try this it will helps you

int index_of = grid_statement.CurrentRow.Cells["ColumnName"].ColumnIndex;

Upvotes: 2

Adil
Adil

Reputation: 148120

You are probably trying to access the columns collection before binding the data source. At this time gridview wont have any columns. Assign dataSource and bind the grid and then check the index of column.

grid_statement.DataSource = dataTable;
grid_statement.DataBind();
int index_of = grid_statement.Columns[the_name].Index;

To avoid exception you should first check if you got column then get its index.

int index_of = -1; 
if(grid_statement.Columns[the_name] != null)
    index_of = grid_statement.Columns[the_name].Index;

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

If your are trying to get column by it's name, then either your grid is null, or there is no column with name equal to the_name in your grid. In both cases you will not be able to get index of non-existing column. To avoid exception in case there is no column with provided name, you can check if column exists before trying to get its index.

var column = grid_statement.Columns[the_name];
int index_of = column == null ? -1 : column.Index;

If you are trying to get column by it's header text (which is not same as column name) you should search for column with same header. And if column was found, get it's index:

var column = grid_statement.Columns
                .Cast<DataGridViewColumn>()
                .FirstOrDefault(c => c.HeaderText == the_name);

int index_of = column == null ? -1 : column.Index;

Upvotes: 3

Related Questions