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:
ToArray
on the IEnumberableCast
.this.colDesired.Index
has a valid value. Else it will raise runtime exception.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: