Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datagridview column index

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?

like image 557
harf Avatar asked Jul 07 '11 22:07

harf


4 Answers

To retrieve a DataGridView column by name you simply reference it through the columns collection indexer:

datagridview1.Columns["columnName"]

Then you can get the column index from that column:

datagridview1.Columns["columnName"].Index;

Do note that if you use an invalid column name then this reference will return null, so you may want to check that the column reference is not null before using it, or use the columns collection .Contains() method first.

like image 100
David Hall Avatar answered Oct 15 '22 15:10

David Hall


If I am right, e.ColumnIndex will also work for this. you can check the MSDN Documentation here

like image 36
Mr_Green Avatar answered Oct 15 '22 16:10

Mr_Green


You can get the index by using the Index property of the DataGridViewColumn widget, as such:

ColumnName.Index

This avoids the need for checking whether the column name is valid at runtime as it will generate a compilation error if the column does not exist. This also makes refactoring easier.

I recommend you give the columns a sensible name (for example DCOL_SomeName) so that you can easily distinguish them. Including the name of the DataGridView widget would help if you have multiple DataGridView widgets on the same form.

like image 43
Vlad Schnakovszki Avatar answered Oct 15 '22 16:10

Vlad Schnakovszki


create a static class below the code

public static class MyTools
{
    public static int IndexByName(this DataGridView dgv, string name)
    {
        foreach(DataGridViewColumn col in dgv.Columns)
        {
            if(col.HeaderText.ToUpper().Trim() == name.ToUpper().Trim())
            {
                return col.Index;
            }
        }
        return -1;
    }
}

and then call it with your dataGridView

int index = datagridview1.IndexByName("columnName");
like image 42
djsony90 Avatar answered Oct 15 '22 16:10

djsony90