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:
ToArrayon the IEnumberableCast.this.colDesired.Indexhas a valid value. Else it will raise runtime exception.DatagridViewCell.Valuewill be null, hence you should get an appropriate formatted value (DatagridViewCell.FormattedValue), depending on theFormatTypeof your cell which here is text type, to handle null cases.DatagridViewCell.FormattedValueis an object so you will have to convert it to a string first.Do this: