Smart Row Selection: Maintaining Infragistics UltraGrid State After Refresh
... skipping 1000 words about bad solutions ...
The Clean/Best Solution
Here's a pattern that elegantly handles this situation:
public void RefreshGrid()
{
// 1. Store the current entity before refresh
SomeEntity currentEntity = null;
if (dataGrid.ActiveRow != null)
{
currentEntity = dataGrid.ActiveRow.ListObject as SomeEntity;
}
// 2. Refresh the grid
dataGrid.RefreshData();
// 3. Restore selection using entity ID
if (currentEntity != null)
{
dataGrid.ActiveRow = dataGrid.Rows.FirstOrDefault(r =>
((SomeEntity)r.ListObject).Id == currentEntity.Id);
}
}
Why This Pattern Is Best Practice
- Type Safety: Using the strongly-typed entity object instead of raw values
- Identity-Based: Uses unique IDs instead of volatile row positions
- Null-Safe: Handles cases where no row is selected
- Concise: LINQ makes the code readable and maintainable
- Reliable: Works even if data order changes or rows are filtered