开发者

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 column开发者_C百科s: 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?


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.


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


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.


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");


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜