Recently got a question about the selected index property.


the question read something like this


The function

grid.getSelectedIndex()

returns the actual index of the selected row, which is correct when no filter is set.

But if I set a filter (which, of course, reduces the amount of actually displayed data) this function returns still the same number, which is not correct.

Is there a function that returns the index of the selected row while considering any active filters?

For example: I have 10 rows in my grid. When I click on the 5th row then getSelectedIndex() returns 4 (because it’s a zero-based index).

But if I set a filter causing that just this one row is visible and the others rows are not visible anymore (grid.getTotalRecords returns 1), then by clicking on this row the function getSelectedIndex() still returns 4, but should now return 0.


===

The short answer to this question is that  it is possible to do it if you really want the selectedIndex, do grid.getFilteredPagedSortedData() and then do an indexOf grid.getSelectedItem() on that array.


 var filterCnt = grid.getFilteredPagedSortedData({},true,false,true);

  And then

 filterCnt.indexOf(grid.getSelectedItem())

 

The longer answer is a little more involved.  and the primary idea is if  in reality what you need is the item that is selected just use the getSelectedItem method.  we made a conscious decision to deviate from the way some other products store  the selected state of the grid.  depending on what you set as the value for your selectedKeyField,  we will either store the actual object that is selected or a key property on the object that is selected.  internally we never store the index of the object that selected.  this is always calculated.  this allows us to maintain selection regardless of the state of the data provider if it's filters sorted, or paged in any manner.

 

The selectedIndex is not a reliable method of identifying the selected object, because that index changes everytime you do a sort or a filter or page. In other words. If the selected index is on page 0, and you move to page 2, the selectedIndex means nothing because the object is no longer on the page. This gets further complicated when server paging is invovled. So our recommendation is always use grid.getSelectedItem instead of grid.getSelectedIndex, because majority of the time, you are using the index to get to the actual item anyway.