Get index of first row that matches with a pattern
-
14-07-2021 - |
سؤال
I have a datagridview with some columns and rows. One of the columns is string type (DataGridViewTextBoxColumn
). I would like to iterate over all the rows of this DataGridViewTextBoxColumn
to find the index (row index) of the first element that matches with a specific string so I do:
int rowIndex = this.dataGridView1.Rows
.Cast<DataGridViewRow>()
.ToArray()
.First(row => row.Cells[this.colDesired.Index].Value == stringToSearch)
.Index;
but an error is raised.
I want to use Linq and lambdas.
المحلول
Your solution works for me well. Few things to notice:
- You don't have to do a
ToArray
on the IEnumberableCast
. - Ensure
this.colDesired.Index
has a valid value. Else it will raise runtime exception. - Default value of
DatagridViewCell.Value
will be null, hence you should get an appropriate formatted value (DatagridViewCell.FormattedValue
), depending on theFormatType
of your cell which here is text type, to handle null cases. DatagridViewCell.FormattedValue
is an object so you will have to convert it to a string first.
Do this:
int rowIndex = dataGridView1.Rows.Cast<DataGridViewRow>().First(row => row.Cells[this.colDesired.Index].FormattedValue.ToString() == stringToSearch).Index;
نصائح أخرى
This should work:
int rowIndex = this.dataGridView1.Rows.OfType<DataGridViewRow>()
.First(row => row.Cells[this.colDesired.Index].Value == stringToSearch).Index;
لا تنتمي إلى StackOverflow