1) Trying to do a search in a DataGridView using LINQ operations:

 var find = UsersDataGridView.Rows.Cast<DataGridViewRow>() .FirstOrDefault(x => x.Cells[cbFilterSearch.SelectedIndex].Value.ToString().Contains(tbSearch.Text)); if (find != null) { find.DefaultCellStyle.BackColor = Color.Red; } 

It colors only one line in red, although there are more finds. How to fix?

2) Is it possible to remake this code in LINQ ?

 for (int i = 0; i < UsersDataGridView.RowCount; i++) UsersDataGridView.Rows[i].DefaultCellStyle.BackColor = Color.White; 

    2 answers 2

    It colors only one line in red for the reason that you take FirstOrDefault - this means that as a result we get either one line or null if the item is not found (the default value is Default ).

    Therefore, we slightly modify your code as follows:

     var indexFilter = cbFilterSearch.SelectedIndex; // вынес для удобства var findResult = UsersDataGridView.Rows.Cast<DataGridViewRow>() .Where(x => x.Cells[indexFilter].Value.ToString().Contains(tbSearch.Text)).ToList(); // меняем цвет так (по Вашему примеру) for (int index = 0; index < findResult.Count; index++) { findResult[index].DefaultCellStyle.BackColor = Color.Red; } // или меняем цвет вот так (немного удобнее) foreach (DataGridViewRow row in findResult) { row.DefaultCellStyle.BackColor = Color.Red; } 

    Simply, we replaced FirstOrDefault with Where(predicate).ToList() and instead of a single element - got a collection of elements that satisfy the search condition.

    Regarding the second question, you can offer this version of LINQ :

     UsersDataGridView.Rows .Cast<DataGridViewRow>() .ToList() .ForEach(x => x.DefaultCellStyle.BackColor = Color.White); 

    Rows 's transform the Rows element from the DataGridViewRowCollection type to the list of DataGridViewRow elements and change the BackColor value of each collection element in the ForEach loop.

    • Thank you very much. - Maxim
    • one
      The last paragraph is strange. You are here and do not change the collection item. The findResult [index] link will remain unchanged. You change the field value of the object. - Artyom Okonechnikov
    • @Maxim, added LINQ answer, can be redone, just Cast needed. - Denis Bubnov
    1. FirstOrDefault - returns the first element of the collection or the default value if the collection is empty. For your task, the Where method that filters the collection by predicate is appropriate.

    2. You can set the color of all cells at once

    • Thank you very much. - Maxim