Question

I am trying to search every cell in my datagridview for a value "test". However it is only searching the first row... (i believe it is searching all the columns) Any ideas on how I can fix this?

dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
            string searchValue = "test";

            int searching = -1;
            while (searching < 7)
            {
                searching++;
                try
                {
                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        if (row.Cells[searching].Value.ToString().Equals(searchValue))
                        {

                            row.Cells[searching].Selected = true;
                            break;
                        }
                    }
                }
                catch (Exception exc)
                {
                   // MessageBox.Show(exc.Message);
                }
            }
Was it helpful?

Solution

use this snippet.. basically we iterate through every row/column and set its value as selected if we find a match.

dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
string searchValue = "test";

for (int row = 0; row < dataGridView1.Rows.Count; ++row)
{
 for (int col = 0; col < dataGridView1.Columns.Count; ++col)
 {
  var cellValue = dataGridView1.Rows[row].Cells[col].Value;

  if (cellValue != null && cellValue.ToString().Equals(searchValue))
  {
   dataGridView1.Rows[row].Cells[col].Selected = true;

   // if you want to search every cell for the searchValue then you shouldn't break.
   // break;
  } 
 }
}

you can also do the above as follows, using concise LINQ code:

dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
string searchValue = "test";

dataGridView1.Rows.ToList().ForEach(row => row.Cells.ToList().ForEach(cell => 
{
 cell.Selected = (cell.Value != null && cell.Value.ToString().Equals(searchValue));
}));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top