Looping through Data Grid cell contents

Jun 26, 2010 at 6:47 PM
Edited Jun 30, 2010 at 11:23 PM

Here is a method that will find the first occurrence of a string in the data grid:

private void findTerm(string searchTerm)
{
    bool termFound = false;

    for (int row = 1; row < dataGrid.Rows.Count; row++)
    {
        for (int column = 0; column < dataGrid.Columns.Count; column++)
        {     
            CellContext cell = new CellContext(dataGrid, new Position(row, column));                    
        
           if (cell.Value.ToString().Contains(searchTerm))
           {
                dataGrid.Selection.SelectRow(row, true);
                dataGrid.Selection.FocusRow(row);
                termFound = true;
                break;
           }
        }

        if (termFound == true)
        {
            break;
        }
    }
}

EDIT: I've updated the code to a solution that seems to work. Is there a better solution?

I imagine that working with the content of the data source would be preferred, since that can be done on a thread separate from the UI.

But what if the dataGrid is sorted by the user or some rows are hidden? Then the dataGrid cell positions would not correspond to the data source. I imagine I can just use the unique line numbers I store for each object in the data source and reference them with the rows displayed by the dataGrid. I might give that a try. Any additional thoughts are welcome!

UPDATE: I've implemented a solution that goes through the data source instead of the data grid to find a match, which does make it faster. Although I still have to loop through one column of the data grid to find the appropriate line number that is referenced by the object in my data source. I guess looping through one column is better than looping through the entire data grid!

Thanks for the help and all the hard work!