Skip to main content Skip to footer

Retain Selection on Sorting, Grouping and Filtering in C1DataGrid

We're often in a situation where we've selected a row and then as soon as we apply sorting or filtering on the grid, a row with different data gets selected. This is because selection works on the basis of row index in most of the Grid controls and it applies for C1DataGrid for Silverlight as well. So if we select the first row and apply sorting, grouping or filtering, we will observe that the first row remains selected. Now, suppose if we fetch the data of the selected row, we would get different data. This behavior will occur every time we apply any data operation on the grid. What do we do then!! Well, we have a very simple and a straight forward solution for this. I think you must have guessed it by now. The solution is to save the selected row in a temporary variable and then restore it after the data operation is complete. Keep reading to find out how this can be done.

Retaining Selection

The basic idea is to save the hashcode(since it is unique) of the underlying DataItem of the selected row when the data operation is being done. Once the Data Operation is complete, then select the row whose DataItem has the same hashcode as the saved one. The hashcode is saved in the SortChanging, GroupChanging and FilterChanging events and is restored in the SortChanged, GroupChanged and FilterChanged events.


int hashCode;  

public void SaveSelection()  
{  
   if (grid.Selection.SelectedRows.Count > 0)  
     hashCode = grid.SelectedItem.GetHashCode();  
}  

public void RetainSelection()  
{  
    int flag = 0;  

    if (hashCode != null)  
    {  
       for (int i = 0; i < grid.Rows.Count; i++)  
       {  
          if (grid.Rows[ i ] .DataItem.GetHashCode() == hashCode)  
          {  
             grid.Selection.Clear();  
             grid.Selection.Add(grid.Rows[ i ], grid.Rows[ i ]);  
             flag = 1;  
             break;  
          }  
          else  
          {  
            flag = 0;  
          }  
       }  

       if (flag == 0)  
       {  
          grid.Selection.Clear();  
       }  
    }  
 }  

 void grid_SortChanging(object sender, DataGridSortChangingEventArgs e)  
 {  
    SaveSelection();  
 }  

 void grid_SortChanged(object sender, DataGridSortChangedEventArgs e)  
 {  
    RetainSelection();  
 }  

 void grid_GroupChanging(object sender, DataGridGroupChangingEventArgs e)  
 {  
    SaveSelection();  
 }  

 void grid_GroupChanged(object sender, DataGridGroupChangedEventArgs e)  
 {  
    RetainSelection();  
 }  

 void grid_FilterChanging(object sender, DataGridFilterChangingEventArgs e)  
 {  
    SaveSelection();  
 }  

 void grid_FilterChanged(object sender, DataGridFilterChangedEventArgs e)  
 {  
    RetainSelection();  
 }  

You can download the sample below for complete implementation. Download Sample

MESCIUS inc.

comments powered by Disqus