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?
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With