If your purpose is to find the
Cell
in the
DataGridView
containing a given
Text
, then I think it is better to use the
Rows
and
Cells
collection of
DataGridView
to generate a List of DataGridViewCell which contain the given text. Then on a button click set the
CurrentCell
of
DataGridView
to the found cells as shown below:
List<datagridviewcell> containingCells = new List<datagridviewcell>();
int currentContainingCellListIndex = 0;
ButtonFindText.Click += (sender, args) => {
containingCells.Clear();
currentContainingCellListIndex=0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Value == DBNull.Value || cell.Value == null)
continue;
if (cell.Value.ToString().Contains(textToFind)) {
containingCells.Add(cell);
}
}
}
if (containingCells.Count > 0)
dataGridView1.CurrentCell=
containingCells[currentContainingCellListIndex++];
};
ButtonFindNext.Click += (sender, args) => {
if (currentContainingCellListIndex < containingCells.Count ())
dataGridView1.CurrentCell=
containingCells[currentContainingCellListIndex++];
};
FindUsingLinqButton.Click += (sender, args) => {
currentContainingCellListIndex=0;
containingCells = dataGridView1.Rows.OfType<DataGridViewRow>().SelectMany (
dgvr => dgvr.Cells.OfType<DataGridViewCell>().Where (dgvc =>
dgvc.Value != DBNull.Value && dgvc.Value != null &&
dgvc.Value.ToString().Contains(textToFind))).ToList();
if (containingCells.Count > 0)
dataGridView1.CurrentCell=
containingCells[currentContainingCellListIndex++];
};
}