Get index of first row that matches with a pattern

526 views Asked by At

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.

2

There are 2 answers

1
nawfal On BEST ANSWER

Your solution works for me well. Few things to notice:

  1. You don't have to do a ToArray on the IEnumberable Cast.
  2. Ensure this.colDesired.Index has a valid value. Else it will raise runtime exception.
  3. Default value of DatagridViewCell.Value will be null, hence you should get an appropriate formatted value (DatagridViewCell.FormattedValue), depending on the FormatType of your cell which here is text type, to handle null cases.
  4. 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; 
1
Reuf Slamnik On

This should work:

int rowIndex = this.dataGridView1.Rows.OfType<DataGridViewRow>()
       .First(row => row.Cells[this.colDesired.Index].Value == stringToSearch).Index;