CheckBox selection in DataGrid and List

Several folks have asked how to use Checkbox renderers to handle multiple selection in a DataGrid or List. There are some solutions out there already, but here’s mine. Usual caveats apply.
Download Source
Run Demo

78 Responses to CheckBox selection in DataGrid and List

  1. Danny Gold says:

    Do you have any suggestions for how to maintain the “selected” style you usually get with selected items in a list, the hightlight, etc? I posted a solution to this on my blog, but it’s a hack at best. I think the ListBase is hardcoded to look for a CTRL or SHIFT modifier so I intercept mouse events and set those properties.
    I’d love to hear your thoughts on a ‘cleaner’ approach, but that’s what I had to do to get the job done.
    Thanks for your thoughts as always.
    Alex responds:
    In my example, I override drawSelectionIndicator to turn off the visuals. If you remove that override, you should see the items show selection as they are checked.
    The basic principle of my example is to essentially make “dead” checkboxes. They don’t handle mouse or key events at all and just let the List or DataGrid handle the clicks as if it was a regular renderer, except I force the control to think that the ctrl key is pressed all the time.
    It sounds like you took a similar approach. I glanced at your code briefly and saw that there was some room for optimization so went ahead and posted mine.

  2. Danny Gold says:

    Good stuff. I updated my example to override the selectItem function as well. Glad you posted your approach so I can make those changes in our project as I find myself using the checkboxes for most of our datagrids. Great to have such an active community to build on.

  3. Michael says:

    The following happens when reordering the columns in the grid:
    TypeError: Error #1034: Typumwandlung fehlgeschlagen: mx.controls.dataGridClasses::DataGridItemRenderer@2de8cf11 kann nicht in mx.controls.CheckBox umgewandelt werden.
    at CheckBoxDataGrid/drawItem()
    at mx.controls.dataGridClasses::DataGridBase/drawVisibleItem()
    at mx.controls.dataGridClasses::DataGridBase/makeRows()
    at mx.controls.dataGridClasses::DataGridBase/makeRowsAndColumns()
    at mx.controls::DataGrid/makeRowsAndColumns()
    at mx.controls.listClasses::ListBase/makeRowsAndColumnsWithExtraRows()
    at mx.controls.listClasses::ListBase/updateDisplayList()
    at mx.controls.dataGridClasses::DataGridBase/updateDisplayList()
    at mx.controls::DataGrid/updateDisplayList()
    at mx.controls.listClasses::ListBase/validateDisplayList()
    at mx.managers::LayoutManager/validateDisplayList()
    at mx.managers::LayoutManager/doPhasedInstantiation()
    at Function/
    at mx.core::UIComponent/callLaterDispatcher2()
    at mx.core::UIComponent/callLaterDispatcher()
    Alex responds:
    Like I said, caveats apply. I would set draggable=false on the column so it stays as the first column.

  4. saverio says:

    Hi. This is very useful if the list is used “alone”. I have a somehow different situation.
    The data provider is to be changed externally (by a filter function), when the user writes in a textbox (shown items have the typed string as a substring). On the other side, the ‘checked’ state of the box must persist whether or not the item are filtered out, so using internal ‘selectedItems’ is out of question, because when items are filtered out they are of course automatically deselected.
    Using just a custom function for selection with inthe checkBox renderer gives the ‘show’ part, but the ‘change’ part is much harder. Do you have any idea? If I just use the renderer as editor, the diplays shows garbage in the renderers…
    Typically the list of ‘checked’ items lives in an ArrayCollection somewhere in the component.
    Alex responds:
    I should have mentioned the limitations of this version. It doesn’t allow the kind of functionality you are looking for nor does it allow sorting by selected entries. Both require storing some knowledge of the selection state in the dataProvider.
    If you have a slot in your dataobjects to store selection state, great, and then I might not use the List’s selection code at all.
    If you don’t have a slot for your dataobjects, you’ll need a separate collection. One of these days, maybe I’ll show how to do a mergedCollection. I thought Deepa was going to post an example, but I didn’t see it on her blog.

  5. Aymsley Edwards says:

    Hi. This has worked great for me but I have been trying to work out how to have all the check boxes defaulted to selected.
    I’ve tried a couple of things but can’t get it to work.
    Can you suggested a solution ?
    Alex responds:
    I would just create an array of numbers from 0 to n and pass that into selectedIndices.

  6. Vinay says:

    Hi Alex,
    I have a question regarding the selection of a checkbox within the datagrid by default. As in, I am trying to get a checkbox to be checked by default using a dataprovider. I have an array with one of the elements as { source: “WH”, repCost: “10.99”, sourceableQuantity: “35”, totalQuantity: “20”, leadTime: “15”, relevant: true}. I convert this Array to an ArrayCollection and pass this as a dataprovider to CheckBoxDataGrid. I have dataField=”relevant” editorDataField=”selected” rendererIsEditor=”true”
    width=”20″ sortable=”false” editable=”true” itemRenderer=”controls.itemRenderers.CheckBoxRenderer” for the checkbox DataGridColumn. However, it doesnt display the checkbox as checked. What am I doing wrong?. Sorry if this is a noob question. Thanks for all your help.
    Alex responds:
    You might be better off using this post:

  7. Varun Shetty says:

    thank you for this code.. appreciate it .. saved me a load of time.. 🙂
    btw. rite now jus tryin to figure out and change it.. why do you have a checkbox selection on keyboard press.. i mean when you keypress ‘S’, ‘I’ or any character it selects the particular item in the list box. I jus want to get it into focus but selection only by mouse click..
    i’ll try to figure it would will shout fr help if required.. 🙂
    Alex responds:
    I didn’t set up that functionality, it is built into the list classes. They search for entries based on the last letter typed and selected them. You can turn that off by overriding the findString() method and have it do nothing.

  8. Edward says:

    Hi, It is really a great knowledge source all the samples you write. Thanks for all the help and greetings from México.
    My question, once, I have this array of index, how can I send them all to a PHP, I’ll take care the php part but what about the flex part, I would like to send not the index but the names so I can receive them with a php function and then submit them to a database, I would like to use it like a shopping cart selector.
    Alex responds:
    If you are using this example, I would get the selectedItems array from the DataGrid. It will be an array of references to items in the dataprovider, and you can pull the appropriate fields and post them back to your server.

  9. Atro says:

    I dont understand the code, but I can tell you this has been a life saver. Thank you

  10. Dmitriy says:

    Thanks for example. But you had some mistake in using sorting: number of selected lines defining uncorrectly.
    Alex responds:
    OK, thanks.

  11. Max says:

    Hi Alex,
    Thanks for this code .
    I have a question regarding the editing of other editable dataFields .
    if i use an itemEditor in dataGrid and try to select
    it to change it’s value , the checkBox column will be selected as well .
    is there any property .. to restrict selectItem function to fire only on checkbox column ?
    I was playing with this line

    return super.selectItem(item, false, true, transition);

    but no luck to tell datagrid , that is not a checkbox .
    you mentiend using if (item is CheckBox) but still same thing .
    I retrieved my Data from Coldfusion and everything else works .
    I really appreciate for your help .
    Thank you.

  12. دردشة says:

    OpenFlux е Degrafa най-добър приятел. Чудите се как започваш да се направят всички тези готини собствени виждания за вашата OpenFlux компоненти? Yup, тези две бяха така означаваше, че една OpenFlux идва с Degrafa печени в. Помислете си напълно, което има право да направи хората призива Ви получер lier-различно, когато им каже, че наистина е Flex ап. Това е начин извън стайлинг, начин, след одиране, че е искал ние stole, че някои от бъдещите версия на Flex или нещо
    Thanks ..
    Alex responds:
    You’re welcome. I wish I knew for what…

  13. Chris says:

    I have a quick question…I’m very new to Flex, and I was wondering how to adjust your code to display a CheckBoxList for an array of strings instead of an array of objects. Thanks for your time.
    Alex responds:
    I think you can just use an array of strings. If it doesn’t work, ask on FlexCoders for help.

  14. chenfang zou says:

    I have a simple question, hope someone can help me.
    I have a regular datagrid, one of the column is checkbox, another column is editable. My requirement is that when the checkbox is checked/selected, I want to clear the editable column. I was able to change the data(array collection) behind the datagrid, but the UI is not refreshed. How to refresh the UI inside a customized itemrender?
    Alex responds:
    You might have to call itemUpdated. If you have further questions, try posting on FlexCoders

  15. Francis says:

    I’m very new to flex. I would like to add a comboxbox that controls the selection in the datagrid. I have “All” and “None” in my combobox and if I select “All”, it should checkmark all the checkboxes in the datagrid. Do you have any suggestions? Thanks for your time
    Alex responds:
    I would make an array of numbers from 0 to length-1 and set that as selectedIndices if you want to select all

  16. jbr says:

    thanks for the code
    it’s realy helpful

  17. Kavitha says:

    Hi Alex,
    Thanks for your code. I want checkbox column as the last one in datagrid.Then that case its giving error like TypeError: Error #1034: Type Coercion failed: cannot convert mx.controls.dataGridClasses::DataGridItemRenderer@44115b1 to mx.controls.CheckBox
    Could you suggest any solution?
    Alex responds:
    Depends on the rest of the stack trace. Somebody’s code is expecting a checkbox but getting a regular cell.
    You’ll get faster response if you ask on FlexCoders

  18. sudha says:

    Hi Alex,
    Thanks for the code. It saves lot of time for a new bee like me.I have a question. I want to disable some of the checkboxes based on one filed in my data grid. For this one, I wrote teh necessary logic in updatedisplaylist() of Sample code is given below.
    if(!( ci sTextField)){
    if(so and so){
    This one is giving random results when I scroll the datagrid. If I dont scroll everything is working as expected.
    Please advice me in fixing this.
    Alex responds:
    See the other item renderer posts. Renderers get recycled and need to be completely data-driven.

  19. Agil says:

    hi Alex thx for your code,
    help me do this in Flash using AS3? thx very much…
    Alex responds:
    Sorry, I don’t have the time for that

  20. sascha/hdrs says:

    I’m trying to get your code working in a fully AS-written Flex application, so I use no mxml files, only AS.
    If I use …
    dgCol.itemRenderer = CheckBoxRenderer;
    I get an error that CheckBoxRenderer is not a ClassFactory. If I try …
    dgCol.itemRenderer = new ClassFactory(CheckBoxItemRenderer);
    It compiles, but the CheckBoxes don’t show up. How is this done correctly in AS3 only? The docs mostly have only mxml source examples either so they are not much of a help.
    Thanks for any tips!
    Alex responds:
    Not sure what you mean by AS3-only, but it sounds like the default Styles are not compiled in, which MXMLC takes care of.

  21. Ashok says:

    Hi Alex,
    i am using item renderer checkbox and headerer renderer check box for select/deselect of all the datagrid rows but when i move the vertical scroll bar up and down . i am not able to retain the checked status . it is in consistent when i use scroll. pls help me to over ride this issue .
    thanks in advance
    Alex responds:
    It depends on how you store the selected state and how the item renderers refreshes the checked status. Look more closely at my examples.

  22. Andrea says:

    Hi Alex,
    first of all thanks for your component, I found it very useful for my needs.
    Unfortunately, when I’m using the arrow keys UP & DOWN, and the Page UP & DOWN when the datagrid got the focus, the checkboxes are un/selected.
    Can you help me to avoid this behaviour? I tried your suggestion to Vinay ( override findString() ) but it doesn’t work.
    Alex responds:
    I don’t think you want it to change the checkboxes as you use UP and DOWN. It wouldn’t give you any control over doing disjointed selection sets. The way the code works now is that you hit space bar to toggle the checkbox.

  23. JMP says:

    Just curious, is it by design that none of your demos run in IE7? (XP SP3)
    Alex responds:
    I think IE7 has security that prevents hitting a link to a SWF. I don’t use it so I don’t know if there’s a solution to just hitting a SWF link. If our blog software made it easier to upload files, then I’d upload the html and js wrappers that would get it to work.

  24. Simon Bailey says:

    Hi Alex,
    Thanks for you work here, as many mention, it’s much appreciated.
    One quick query re:
    A dg with multiple columns & rows of Check Boxes.
    Select ONE check box.
    Scroll (horizontally or vertically) would cause all check boxes on the row to become selected?
    BTW it is using your example simply adding on an extra column (few minor tweaks).
    Alex responds:
    This example binds the checkbox’s selection state to whether the row is selected or not. If you didn’t wire it up your version properly, it may not be updating correctly. When you select one checkbox on a row, the others on the row should have become selected right away, and not just after scrolling.

  25. Dimitar says:

    One stupid question, how can I get the selectedItems firstName in one variable?
    Alex responds:
    I’m not sure I understand the question. You’ll get an array of selectedItems and then have to iterate through the array. You can append all of the firstNames into a single string if you want.

  26. Simon Bailey says:

    Thanks for the response Alex. Yes it will select them all on click, I implemented some logic to identify the column to try and prevent this happening (data.column = listData.columnIndex). However, on scroll this logic goes down the pan, so how would I ensure that the selected value is bound to the individual column and row and not the whole row and column?
    Alex responds:
    The checkbox selection must be driven from some selection model or the data. For example, if you’ve added a selectedColumn property then each checkbox should test against that.

  27. Pavan says:

    I have documented my approach for creating a reusable checkbox header renderer along with the sort functionality here…along with the source code as well 🙂
    I have used the approach of programming to an interface and a small work around to preserve the sort functionality

  28. Scott says:

    Hey Alex,
    Very cool example. I am having a problem figuring out how to delete all the selected items in the List control. I gave up on trying to incorporate the checkboxes so I went basic and just had a list with several items. There seems to be a bug with deleting each selected item. I’ve tried several different methods and RemoveItem isn’t working (don’t think I can use removeItemAt because the list’s index count will change as each item is deleted). Any ideas? Sorry, this may be off-topic.
    Alex responds:
    Ask on FlexCoders if you haven’t already, but an array of indices should do the trick. It might be more efficient if the array is in reverse order

  29. Sree says:

    Thanks a lot for the code.
    This seems to working fine but how do i select objects or rows which are selected in a Grid?
    Here is my case:
    I have DatGrid with dataProvider as List of custom objects. I want to give the user an option on selecting objects with a checkbox in first column (which is not tied to any property in Object) and on Select/De-select it shows indices of all the Objects. But when i sort these indices get re-calculated. At the end i need to get all the objects which are user selected?
    Any idea how to do this?
    Alex responds:
    Not sure I understand. Are you saying that the list of selected indices is invalid after a sort? I would use selectedItems instead of selectedIndices. SelectedItems should still be valid after a sort.

  30. دردشة says:

    I think you can just use an array of strings

  31. chary1112004 says:

    Hi sudha!
    I have just gotten your situation too. May be this is late answer but i wish it will be good with you (if you didn’t have answer) and with another persons.
    You put property liveScrolling=”false” into Advanceddatagrid. It is ok.
    Good luck!
    — chary —

  32. Arunkumar says:

    Hi All,
    Im having one datagrid. That contains one check box and some other text boxes. Values for the datagrid populated on runtime.
    Im having one button named as clear.
    If click the “Clear Button”, the selected check box should be cleared.
    How to do that ?
    Pls Help me….

  33. Suganya says:

    Thanks for your code.
    I want to make the particular row editable when i select the checkbox. Can you please help.

  34. Alan says:

    I like this Alex’s overriding approach except that it is unable to apply for a DataGrid which has a Horizontal ScrollBar.
    It always throws the same error in Kavitha’s comment:
    TypeError: Error #1034: Type Coercion failed: cannot convert mx.controls.dataGridClasses::DataGridItemRenderer@44115b1 to mx.controls.CheckBox
    Sad sad sad! 🙁

  35. Alex Harui says:

    Like I say in every post: Caveats apply. These are just examples, not fully debugged or supported. Maybe I’ll get time to try it and fix it, but if you can debug it and post the solution that would be great.
    You can also post an example of what you’re trying on an adobe forum. Plenty of helpful folks there as well.

  36. Alex Harui says:

    I suppose you could have your renderers for the other columns display an editable control if they are selected. You can call isItemSelected from the renderer

  37. Alex Harui says:

    You can get the selectedItems, find the data item for the row, remove it from the selectedItems array and re-assign the resulting array to selectedItems.

  38. pmanoj84 says:

    Hi Alex,
    I’m now doing a video conferencing project in which only 2 persons can conference at a time, let’s say A and B. At that time, when another person C tries to connect to one of these busy persons (A or B) it will be displayed as a missed call to the corresponding person. Now I can display the name of the 3rd person in a DataGridList. but i want to add a blinking effect to the name of the called person. how can I do that? Plz help me…

  39. John T says:

    I just downloaded the CheckBoxDataGrid and it seems to work fine, except that the the 1st checkbox the Grid is checked when it shouldn’t be. All other checkboxes are unchecked. All checkboxes should be initially unchecked.
    Did I miss something obvious?

  40. RY says:

    Hi Alex,
    Thanks for the code. This seems to be working fine except for the fact I don’t see the checkbox selected as you showed in the example. But, it is displaying all the selected row numbers below. Is this version compatible with Flex 2?
    Appreciate your feedback.

  41. Alex Harui says:

    There’s a blinking item renderer example in the item renderer posts on this blog.

  42. Alex Harui says:

    Hard to say. I haven’t seen any other reports of this. Are you sure you’re not setting selectedIndex to 0 at some point?

  43. Alex Harui says:

    I haven’t tried it on Flex 2. There might have been some change in Flex 3 that keeps it from being backward compatible. Move to Flex 3 if you can. There should be lots of other bugs fixed as well.

  44. Sateesh says:

    Hi, I need Check Box associated with Tilelist which has its own canvas renderer

  45. Alex Harui says:

    Ask on the Adobe forums. You’ll get faster response there.

  46. Ravi says:

    Hi Alex,
    It is Great work.
    this is single checkbox selection. If the check box in the header side and select that checkbox all the fileds has to be selected.This is multi selection. If you have any example, please update me.

  47. Diana says:

    Hi Alex ,
    I would like to retain the checkboxes that were selected at a later point of time . So i set a property isSelected in my vo. But then i am not understanding where this checkbox selected property is being set . can u please guide me on this

  48. Alex Harui says:

    In this example, selection is tracked by selectedIndices and selectedItems on the DataGrid itself. There is another post on my blog that sets properties in the VOs

  49. Mark Krasny says:

    Hi Alex,
    I also got: Type Coercion failed:
    cannot convert mx.controls.dataGridClasses::DataGridItemRenderer@b1d0601 to mx.controls.CheckBox.
    in: CheckBoxDataGrid.drawItem()
    at: CheckBox(item).invalidateProperties();
    In my app the item comes into the function as:
    In your case it’s: CheckBoxRenderer.
    CheckBoxDataGrid.drawItem is called from DataGridBase.drawVisibleItem(uid:String,…):
    drawItem(visibleData[uid], selected, highlighted, caret, transition);
    Here’s how I used it:
    <grid:CheckBoxDataGrid id=”valueGrid” width=”100%” height=”100%”
    dataProvider=”{valueColumns}” … >
    <mx:DataGridColumn dataField=”name”/>
    <mx:DataGridColumn dataField=”percent” itemRenderer=”com…..grid.CheckBoxRenderer”/>
    Any idea?
    Thanks a lot,

  50. How can I retrieve the values of the grid? In this case, wanted to take the values of filed1.Can be used also in the List?

  51. Niche says:

    I want to make datagrid with checkboxes in front in MXML,pl help

  52. Alex Harui says:

    I think there are assumptions in the code that the column of checkboxes is the very first column

  53. Alex Harui says:

    The checked items are in selectedItems. You can probably adapt this code to work in List.

  54. Alex Harui says:

    I’m not sure what you mean.

  55. Found it a great launch
    I thank you very much
    Appreciation and respect
    I liked your topic
    I wish you success

  56. Patrick says:

    how can I automatically store in a data variable “selected”, the (selected/unselected) status of the items in my datagrid ?
    For example, I have as dataProvider an ArrayCollection and each element has:
    name=”item name” selected=”false”
    as attributes. I would like to “bind” selected attribute with the datagrid selection state for each element.

  57. shail says:

    How can i enabled or disabled my checkbox inside grid on certain condition. condition has no relation with checkbox data

  58. Alex Harui says:

    All aspects of a renderer should be data-driven, so on the dataChange event, figure out if you should be disabling or enabling the renderer. You may also need to block the changing of the selectedItem. There is a separate post for how to disable list selection

  59. شات says:

    i I think you can just use an array of strings

  60. Jeff says:

    Thanks Alex. Two suggestions based on my experience with this so far:
    1. CheckBoxRenderer is made to implement IListItemRenderer and the drawItem override in CheckBoxDataGrid is removed. This fixes the issues mentioned above with rendering on scroll or move.
    2. The selectItem override in CheckBoxDataGrid is changed to use ‘if (item is CheckBoxRenderer)’ instead of just CheckBox. Just makes it more specific in case someone attempts to use an mx.controls.CheckBox as a renderer for another column, causing it to modify selection as well (not that they should, though, since it does not implement IListItemRenderer).


  61. All aspects of a renderer should be data-driven, so on the dataChange event, figure out if you should be disabling or enabling the renderer. You may also need to block the changing of the selectedItem. There is a separate post for how to disable list selection

  62. krishna says:


  63. Mark says:

    Hi Alex,

    thanks for all your great posts!

    How about updating this to work with Flex 4?



  64. شات says:

    how can I automatically store in a data variable “selected”, the (selected/unselected) status of the items in my datagrid ?
    For example, I have as dataProvider an ArrayCollection and each element has:
    name=”item name” selected=”false”
    as attributes. I would like to “bind” selected attribute with the datagrid selection state for each element.

  65. Aryan says:

    Hi Alex,
    Thanks for the great post. I am, however, facing one issue. Whenever, I scroll the page, NOT scroll on CheckListBox, the checkmarks on the checkboxes are not retaining. Any suggestions will be helpful.

    • Alex Harui says:

      Do the checks come back if you then scroll the list? Is selectedIndices changing when you scroll the page?

  66. hi Alex thx for your code,
    help me do this in Flash using AS3? thx very much…

  67. I think you can just use an array of strings

  68. ren says:

    Hi Alex,I have a datagrid with one of the columns is an Itemrenderer(checkbox in it). My problem is when I am navigating to each row using the Keyborad, I am not able to select the checkbox using keyborad. Pleas let me know how to solve this

    Thanks in advance Alex