How to get ColumnIndex
of a Column
by ColumnName
from a DataGridView
?
Here's the pseudo-code:
ColumnIndex = ColumnName("SampleName");
You can use IndexOf
. Like this:
var dataGridViewColumn = dataGridView1.Columns[ColumnName];
if (dataGridViewColumn != null)
{
int index = dataGridView1.Columns.IndexOf(dataGridViewColumn);
}
Or use Index
and Null-conditional operator( ?.
) like this:
var index = dataGridView1.Columns[ColumnName]?.Index;
To get the index of a column
myDGV.Columns.IndexOf(myDGV.Columns["SampleColumn"];
or more simply like you said
myDGV.Columns["SampleColumn"].Index;
The simplest way to do that:
myData.Columns.IndexOf(/*DataGridViewColumn*/)
myData.Columns[/*ColumnName*/].Index
Or:
private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int ColumnIndex= dataGridView.CurrentCell.ColumnIndex;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.