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

  1. Type Safety: Using the strongly-typed entity object instead of raw values
  2. Identity-Based: Uses unique IDs instead of volatile row positions
  3. Null-Safe: Handles cases where no row is selected
  4. Concise: LINQ makes the code readable and maintainable
  5. Reliable: Works even if data order changes or rows are filtered

Comments

  1. Markdown is allowed. HTML tags allowed: <strong>, <em>, <blockquote>, <code>, <pre>, <a>.