Flex : How to pre-select an Item in DataGrid

On December 28, 2007, in Flex, by Anuj Gakhar

If you want to pre-select an item in a Datagrid when it loads for the first time, this is how you can do it. The idea is really simple, just set the selectedIndex property of the Datagrid to the index you want and then scroll the DataGrid to the selectedIndex. Took me a while to figure it out. However, turns out the you need to call validateNow() before you call the scrollToindex() on DataGrid.

Sample code posted below.

[xml]
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
initialize="doInit();" creationComplete="setSelectedItem()">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;

// this holds the grid data
[Bindable]
private var myData:ArrayCollection = new ArrayCollection();
// change this name here to change the selected item on load
[Bindable]
private var initialFName:String = "Joe9";

private function doInit():void
{
myData.addItem({fname:"Joe",lname:"Bloggs"});
myData.addItem({fname:"Joe1",lname:"Bloggs"});
myData.addItem({fname:"Joe2",lname:"Bloggs"});
myData.addItem({fname:"Joe3",lname:"Bloggs"});
myData.addItem({fname:"Joe4",lname:"Bloggs"});
myData.addItem({fname:"Joe5",lname:"Bloggs"});
myData.addItem({fname:"Joe6",lname:"Bloggs"});
myData.addItem({fname:"Joe7",lname:"Bloggs"});
myData.addItem({fname:"Joe8",lname:"Bloggs"});
myData.addItem({fname:"Joe9",lname:"Bloggs"});
}

private function setSelectedItem():void
{
var gData:Object = dGrid.dataProvider;
for(var i:Number=0; i < gData.length; i++)
{
var thisObj:Object = gData.getItemAt(i);
if(thisObj.fname == initialFName)
{
dGrid.selectedIndex = i;
//sometimes scrollToIndex doesnt work if validateNow() not done
dGrid.validateNow();
dGrid.scrollToIndex(i);
}
}
}
]]>
</mx:Script>

<mx:DataGrid id="dGrid" dataProvider="{myData}" visible="true">
<mx:columns>
<mx:DataGridColumn dataField="fname" headerText="FirstName" />
<mx:DataGridColumn dataField="lname" headerText="LastName" />
</mx:columns>
</mx:DataGrid>

</mx:Application>[/xml]

Tagged with:  

43 Responses to Flex : How to pre-select an Item in DataGrid

  1. paravoice says:

    Hi
    I try, but it doesn’t work.
    Do you have any other ways?
    If you have another one, please send me a mail, thanks so much.

  2. Anuj Gakhar says:

    @paravoice, that works for me. Can you tell me exactly if you are getting any error or what?

  3. paravoice says:

    Maybe we have a diffrent situation.
    I use a Tree , not a DataGrid .
    Now I use a stupid method to expend the tree until the item which I want to select is visible , then select the item.
    My english is not good, so I hope you can understand.

  4. Anuj Gakhar says:

    OK, I havent tried this on Tree control but theoretically, it should work the same. I will try to put together an example today if I get some time.

  5. Anuj Gakhar says:

    @paravoice, do you have a code snippet you can show so I can see what you are trying and why its not working.

  6. paravoice says:

    Sorry, last week I was on vocation.
    It’s the most important festival in China.
    Here is a code snippet, the node that the label property’s value is ‘Product Management’ should be selected, but it’s not true.

    Thank you for your help.

  7. paravoice says:

    Oh, it seems the code cannot be pasted.
    I have sent the code to you by mail.

  8. JabbyPanda says:

    The call of “validateNow” before executing “scrollToIndex” is only needed if dataProvider of the List derived component was dynamically changed at the run-time

  9. Mike says:

    It doesn’t seem to work for me neither. When I run this, none of the rows are selected. Could you maybe take a look at my code?

  10. Edu says:

    This post saved my life. validateNow() is needed before scrollToIndex. I had problems using it in a Tree and in an AdvancedDatagrid with HierarchicalData. Also keep in mind that the index you want to scroll to depends on the expanded nodes.

  11. Riester says:

    it doesn`t run for me, but i didn`t see my mistake. I will try it again and check the tipp from Edu

  12. Karthik says:

    a Real Thanks!
    That helped me to think and add a feature…!

  13. Jeff says:

    Thanks, this is exactly what I was looking for. The autoscolling to the selectedIndex worked perfectly! 🙂

    The call to validateNow() was not needed (Flex 3.0)

  14. Edu says:

    In this particular sample validateNow() is not needed, cause you set de data in one event and scrollToIndex in a later event, giving the grid enough time to validate itself.

    If you try to change the dataProvider and scroll in the same update cycle, you will probably need a call validateNow() as the grid wont know how to scroll to the desired index.

  15. ben says:

    I fail in trying to select an item in a List with a ModelsCollection as dataProvider.

    Any idea? Thanks.

  16. chirag patel says:

    ValidateNow() worked perfectly fine. It really solved the issue i was facing with the AdvancedDataGrid control. whenever I was trying to scroll to certain index on refresh of data , i was getting duplicate items on grid. But ValidateNow() fixed my issue. thanks a lot anuj.

  17. Roberto says:

    I adapted this to my problem, and was “terrific”.Congratulations

  18. Gabriele says:

    Thanks a lot, it was exactly what I was looking for!

  19. Bill says:

    This worked perfectly for me. THANKS A LOT!

  20. Jihed says:

    this is exactly what I was looking for!
    Thanks

  21. Amit Deshpande says:

    I trying to focus on Data Grid in flex but it not working. Actually i want scroll the Data Grid using keyboared arrow key.
    without using mouse,means when application is load completely then scoll the data grid using keyboar arrow key (no use of mouse)

  22. Amit Deshpande says:

    Type your comment here


    null:

    I trying to focus on Data Grid in flex but it not working. Actually i want scroll the Data Grid using keyboared arrow key.
    without using mouse,means when application is load completely then scroll the data grid using keyboar arrow key (no use of mouse)

  23. Archana says:

    I am trying this, but this doesn’t work for me. The page does not come with pre-loaded selected index, but when i just move my cursor to the the row, row gets highlighted, Please help me resolve this, have been debugging for long time

  24. Seasons says:

    Best you could change the page title Flex : How to pre-select an Item in DataGrid | Anuj Gakhar's Blog to more generic for your content you write. I loved the the writing yet.

  25. Lexa says:

    private function setSelectedItem():void
    {
    for(var i:Number=0; i < myData.length; i++)
    {
    if(myData[i].fname == initialFName)
    {
    dGrid.selectedIndex = i;

    }
    }
    }

  26. pWEN says:

    I’m trying to use the setSelectedItem() function with an AdvancedDataGrid, but I’m getting a line at “var thisObj:Object = gData.getItemAt(i);”…

    ReferenceError: Error #1069: Property getItemAt not found on mx.collections.HierarchicalCollectionView and there is no default value.

    I believe this is because the ADG’s dataProvider is set as the source property of a GroupingCollection2, and the dataProvider itself is of type HierarchicalCollectionView. I don’t know how to fix this, and would appreciate some help. Thanks.

  27. Pratima says:

    Can you pls. email me the code

  28. Wolfgang says:

    Thanks a lot!! Very helpful 🙂

  29. Jennifer says:

    I’ve had a lot of problems with this one but I finally got it fixed. Thanks a lot, this is just what I need.

  30. Jim says:

    I was having trouble setting the selectedItem of an AdvancedDatagrid after sorting the dataprovider which is a HierarchicalCollectionView.
    The key was to validateNow and then set the selectedItem to the cursor.current object like this:
    ————————————————————
    hierarchicalView = new HierarchicalCollectionView(hierarchicalRecords);
    sortData(hierarchicalView);

    var dataCursor:IViewCursor = hierarchicalView.createCursor();

    // Loop through each item (until current is null)
    while (dataCursor.current)
    {
    if (dataCursor.current.ID == theIDtoFind)
    {
    theADG.validateNow();
    theADG.selectedItem = dataCursor.current;
    break;
    }

    // Go to the next item in the cursor
    dataCursor.moveNext();
    }
    ————————————————————

    I hope this can help someone else.

  31. Gary Edwards says:

    Thanks Anuj, this was driving me mad. Worked first time.

  32. akismet-7edceed6b4d4829918d3524630cf81b9 says:

    I have left and tried to do this on to several times and has not worked for me. I tried the selection process maybe I’m doing something wrong there can you advise.

  33. […] Flex : How to pre-select an Item in DataGrid | Anuj Gakhar – If you want to pre-select an item in a Datagrid when it loads for the first time, this is how you can do it. The idea is really simple, just set the… […]

  34. It perfectly works on other browser other that IE11. Can you provide any suggestion for working in IE11?

Leave a Reply to Jihed Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2011 Anuj Gakhar
%d bloggers like this: