Skip to main content Skip to footer

How to Maintain Row Selection when Sorting FlexGrid

Every user has his own unique requirements. Many customers face this situation where they would like to retain the selected row when C1FlexGrid is sorted. When we apply sorting on C1FlexGrid, the selection is not retained by default. This article explains an approach to ensure that the selected row is retained when C1FlexGrid is sorted.

Step 1: Save the Selected Row Index

Here using C1FlexGrid's MouseClick event, we can save the index the selected row in a global variable rowIndex. This variable will be used later in the AfterSort event. Code snippet for this event is as follows:

void c1FlexGrid1_MouseClick(object sender, MouseEventArgs e)  
  {  
     CurrencyManager cm = (CurrencyManager)BindingContext[this.c1FlexGrid1.DataSource];  
     DataRowView dr = cm.Current as DataRowView;  
     rowIndex = dr.Row.Table.Rows.IndexOf(dr.Row);  
  }  

Step 2: Get the DataRowIndex & set it after Sorting

Here using AfterSort event we will retrieve the DataRowI**ndex of the selected row and then use C1FlexGrid's Select** method to select the row that was selected before sorting. Code snippet for this event is as follows:

void c1FlexGrid1_AfterSort(object sender, C1.Win.C1FlexGrid.SortColEventArgs e)  
  {  
     if (rowIndex > -1)  
      {  
        foreach (C1.Win.C1FlexGrid.Row rw in c1FlexGrid1.Rows)  
          {  
            CurrencyManager cm = (CurrencyManager)BindingContext[this.c1FlexGrid1.DataSource];  
            DataRowView dr = rw.DataSource as DataRowView;  
            if (dr != null)  
             {  
               int currIndex = dr.Row.Table.Rows.IndexOf(dr.Row);  
               if (currIndex == rowIndex)  
                {  
                  CellRange cr = c1FlexGrid1.GetCellRange(rw.Index, 1);  
                  // to scroll the selected row in the visible area  
                  c1FlexGrid1.Select(cr, true);  
                  cr = c1FlexGrid1.GetCellRange(rw.Index, 0, rw.Index, c1FlexGrid1.Cols.Count - 1);  
                  c1FlexGrid1.Select(cr, false);  
                  break;  
                 }  
            }  
        }  
     }  
 }