The following example shows how you can create an editable Flex DataGrid control by setting the editable property on the DataGrid and DataGridColumn objects.
Full code after the jump.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/05/11/creating-an-editable-datagrid-control-in-flex/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white">
<mx:ArrayCollection id="arrColl">
<mx:source>
<mx:Array>
<mx:Object label="Student A" score="85" />
<mx:Object label="Student B" score="48" />
<mx:Object label="Student C" score="71" />
<mx:Object label="Student D" score="88" />
<mx:Object label="Student E" score="24" />
<mx:Object label="Student F" score="64" />
<mx:Object label="Student G" score="76" />
<mx:Object label="Student H" score="76" />
<mx:Object label="Student I" score="93" />
<mx:Object label="Student J" score="88" />
<mx:Object label="Student K" score="48" />
<mx:Object label="Student L" score="76" />
</mx:Array>
</mx:source>
</mx:ArrayCollection>
<mx:DataGrid id="dataGrid"
dataProvider="{arrColl}"
editable="true"
rowCount="8">
<mx:columns>
<mx:DataGridColumn dataField="label"
editable="false" />
<mx:DataGridColumn dataField="score"
editable="true" />
</mx:columns>
</mx:DataGrid>
</mx:Application>
View source is enabled in the following example.
When working with editable DataGrid controls, there are three events which can be useful: itemEditBeginning, itemEditBegin, and itemEditEnd.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/05/11/creating-an-editable-datagrid-control-in-flex/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white">
<mx:Script>
<![CDATA[
import mx.events.DataGridEvent;
private function addEvent(evt:DataGridEvent):void {
eventsArrColl.addItem(evt);
}
private function clearEvents():void {
eventsArrColl = new ArrayCollection();
}
]]>
</mx:Script>
<mx:ArrayCollection id="arrColl">
<mx:source>
<mx:Array>
<mx:Object label="Student A" score="85" />
<mx:Object label="Student B" score="48" />
<mx:Object label="Student C" score="71" />
<mx:Object label="Student D" score="88" />
<mx:Object label="Student E" score="24" />
<mx:Object label="Student F" score="64" />
<mx:Object label="Student G" score="76" />
<mx:Object label="Student H" score="76" />
<mx:Object label="Student I" score="93" />
<mx:Object label="Student J" score="88" />
<mx:Object label="Student K" score="48" />
<mx:Object label="Student L" score="76" />
</mx:Array>
</mx:source>
</mx:ArrayCollection>
<mx:ArrayCollection id="eventsArrColl" />
<mx:ApplicationControlBar dock="true">
<mx:Button label="Clear DataGrid" click="clearEvents();" />
</mx:ApplicationControlBar>
<mx:DataGrid id="dataGrid"
dataProvider="{arrColl}"
editable="true"
rowCount="8"
itemEditBegin="addEvent(event);"
itemEditBeginning="addEvent(event);"
itemEditEnd="addEvent(event);"
itemFocusIn="//addEvent(event);"
itemFocusOut="//addEvent(event);">
<mx:columns>
<mx:DataGridColumn dataField="label"
editable="false" />
<mx:DataGridColumn dataField="score"
editable="true" />
</mx:columns>
</mx:DataGrid>
<mx:DataGrid id="eventsDataGrid"
dataProvider="{eventsArrColl}"
itemRenderer="mx.controls.Label"
verticalScrollPolicy="on"
rowCount="9"
width="100%">
<mx:columns>
<mx:DataGridColumn dataField="columnIndex" />
<mx:DataGridColumn dataField="dataField" />
<mx:DataGridColumn dataField="itemRenderer" />
<mx:DataGridColumn dataField="reason" />
<mx:DataGridColumn dataField="rowIndex" />
<mx:DataGridColumn dataField="type" />
</mx:columns>
</mx:DataGrid>
</mx:Application>
View source is enabled in the following example.

{ 58 comments… read them below or add one }
Hello, I am UI Designer and new to Flex
according to our new project,
we have Combo box which has Any and Specific,and default is Any. and if the User Selects the Specific, we need to Show a “Text Input”, so that User can specify a value to search.
Can you please let me known how to do that By Action Script
Thank a lot in Advance
PSamanth
Prashanth Samanth,
Does this work for you?
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"> <mx:Form width="350"> <mx:FormItem label="User:"> <mx:ComboBox id="comboBox"> <mx:dataProvider> <mx:Array> <mx:String>Any</mx:String> <mx:String>Specific</mx:String> </mx:Array> </mx:dataProvider> </mx:ComboBox> <mx:TextInput id="textInput" visible="{comboBox.selectedItem == 'Specific'}" includeInLayout="{textInput.visible}" /> </mx:FormItem> <mx:FormItem label="Date range:" direction="horizontal"> <mx:DateField id="startDate" /> <mx:DateField id="endDate" /> </mx:FormItem> </mx:Form> </mx:Application>Peter
Hi I have a data grid where one row of data is really long. I want to have a scroll bar so that the data can be seen without increasing the width of the datagrid. I know it automatically allows for height but what can i do for width. I dont want my datagrid to look too big. And also can I group rows of data inside a datagrid, like for ex: can data from 3 rows be grouped in one row and then an expand button be placed. Please reply!
Hi Peter.
First, terrific site. It is my #1 goto site for working examples of real-world Flex scenarios. Thank you for keeping this site updated. It’s is extremely useful to me.
Question: How would I make a datagrid editable, but also add the “restrict” attribute to that field. I see how to do it to text fields, but how do I add it for a datagrid? Like in your example above, restrict the field so that the score had to be numeric? I can see adding an editEnd event that looks to see if it’s a number and then not allowing it. Is that the best way? I was hoping I could just add the restrict tag somewhere easily.
thanks !!!
OK I found the answer. Only the text input component will accept the restrict tag. But you can add an item renderer and do it like this.
http://blog.classsoftware.com/index.cfm/2007/6/11/Flex-Datagrid-Editing-Cells
I like this because it solves 2 problems:
1. Telling the user which fields are editable.
2. Ability to restrict the input chars without more functions.
I made some slight variations on this in order to center the field values.
Hey peterd,
Thanks a lot Dude, that works, I had implemented same code for Multiple Combo Boxes and it’s very easy to use
Thank a lot again
Hello
How to create a Browse Button in Flex, Like we give “type=”file” in HTML, so that we can browse the file from System and upload
This is the HTML Tag: , which I want to include in Flex
Prashanth Samanth,
File uploads and file downloads are handled by the FileReference class. For a few examples, see
http://blog.flexexamples.com/tag/filereference/.
Peter
Peterd,
I even want a Text input before the Browse, so that the User can directly type the path he want to upload…
PSamanth
Peted,
File uploads and Downloads I got this and implemented, please have look at this
http://livedocs.adobe.com/flex/3/html/help.html?content=17_Networking_and_communications_9.html,
thought it will help you too
PSamanth
Yeah yeah check this out. Dig this, Johnson !!
Here’s your dataGrid code:
And here’s your editable cell editor:
<?xml version="1.0" encoding="utf-8"?> <mx:TextInput xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%" restrict="0-9"> <mx:Script> <![CDATA[ import mx.controls.DataGrid; /** * Override data setter to set cell text according to the dataField */ public override function set data(value:Object):void { var dg:DataGrid = owner as DataGrid; text = value[dg.columns[dg.editedItemPosition.columnIndex].dataField]; } ]]> </mx:Script> </mx:TextInput>This is even better since you don’t need to know which order your dataGrid column is and cuts your code by like 90%.
Opps forgot the renderer above.
<?xml version="1.0" encoding="utf-8"?> <mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" implements="mx.controls.listClasses.IDropInListItemRenderer" horizontalAlign="center" verticalScrollPolicy="off" horizontalScrollPolicy="off" preinitialize="init()"> <mx:Label id="CellText" width="93%" paddingLeft="20" /> <mx:Label textAlign="right" text="+" toolTip="Edit" width="12" styleName="editPlusSign" /> <mx:Script> <![CDATA[ import mx.controls.dataGridClasses.DataGridListData; import mx.controls.listClasses.BaseListData; import mx.controls.DataGrid; private var iListData:BaseListData; /** * Implement listData getter from IDropInListItemRenderer */ public function get listData():BaseListData { return iListData; } /** * Implement listData setter from IDropInListItemRenderer */ public function set listData( value:BaseListData ):void { iListData = value; } /** * Add event listener for when data changes */ private function init():void { addEventListener("dataChange", handleDataChanged); } /** * When data changes update the cell text based on the dataField */ private function handleDataChanged(event:Event):void { // Cast listData to DataGridListData. var myListData:DataGridListData = DataGridListData(listData); CellText.text = data[myListData.dataField]; } ]]> </mx:Script> </mx:HBox>Hi. Is there an example of how to do paging on a Flex datagrid? This way you only show a certain number of records per page and have Next/Previous buttons to let the user view more pages of records or jump to a specific page.
hi i want one thing is that after editing the cell value of data grid , i want that changed cell value.please anybody can help me.
Hi Guys,
our team is trying to perform text selection on datagrid cells, but we haven’t found a property, (selectable isn’t) an method, or a flex facility for this task…
is a renderer necessary for this case?
best regards,
SD.Plox
SD.Plox,
There may be easier/better ways, but you can definitely create a custom item renderer and set the
selectableproperty totrue, as seen in the following example:<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:Array id="arr"> <mx:Object c1="One.1" c2="Two.1" c3="Three.1" /> <mx:Object c1="One.2" c2="Two.2" c3="Three.2" /> <mx:Object c1="One.3" c2="Two.3" c3="Three.3" /> <mx:Object c1="One.4" c2="Two.4" c3="Three.4" /> <mx:Object c1="One.5" c2="Two.5" c3="Three.5" /> <mx:Object c1="One.6" c2="Two.6" c3="Three.6" /> <mx:Object c1="One.7" c2="Two.7" c3="Three.7" /> <mx:Object c1="One.8" c2="Two.8" c3="Three.8" /> </mx:Array> <mx:DataGrid id="dataGrid" dataProvider="{arr}" editable="false"> <mx:itemRenderer> <mx:Component> <mx:Label selectable="true" /> </mx:Component> </mx:itemRenderer> </mx:DataGrid> </mx:Application>Or, you could also just create a custom item renderer based on the default DataGridItemRenderer and set the
selectableproperty there instead:<mx:DataGrid id="dataGrid" dataProvider="{arr}" editable="false"> <mx:itemRenderer> <mx:Component> <mx:DataGridItemRenderer selectable="true" /> </mx:Component> </mx:itemRenderer> </mx:DataGrid>Peter
Another option may be an editable DataGrid with a selectable (and non-editable) item editor:
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:Array id="arr"> <mx:Object c1="One.1" c2="Two.1" c3="Three.1" /> <mx:Object c1="One.2" c2="Two.2" c3="Three.2" /> <mx:Object c1="One.3" c2="Two.3" c3="Three.3" /> <mx:Object c1="One.4" c2="Two.4" c3="Three.4" /> <mx:Object c1="One.5" c2="Two.5" c3="Three.5" /> <mx:Object c1="One.6" c2="Two.6" c3="Three.6" /> <mx:Object c1="One.7" c2="Two.7" c3="Three.7" /> <mx:Object c1="One.8" c2="Two.8" c3="Three.8" /> </mx:Array> <mx:Component id="dgIR"> <mx:DataGridItemRenderer selectable="true" /> </mx:Component> <mx:DataGrid id="dataGrid" dataProvider="{arr}" editable="true"> <mx:columns> <mx:DataGridColumn dataField="c1" editable="false" /> <mx:DataGridColumn dataField="c2" itemEditor="{dgIR}" /> <mx:DataGridColumn dataField="c3" itemEditor="{dgIR}" /> </mx:columns> </mx:DataGrid> </mx:Application>Peter
Note: Only the last 2 columns in the DataGrid control are editable. Also, you have to click the cell once to bring up the item editor. Another option could be using a TextInput/TextArea control and setting its
editableproperty tofalse.Peter,
Is is possible to extend this a bit and select text across two or more cells in a given row – still using the typical click and drag highlight method that is used in your examples?
I am aware that the Advanced DataGrid has a multiple select feature, but it relies on conrol-clicking each cell and selected the entire contents of the cell.
Thanks for your help,
Stuart
Hi,
Could you please elaborate more on Custom DataGrid in MXML code?
As per the Above Code DataGrid Columns and values are defined statically but when Webservice is used and returning data in DataGrid what to be written in the code to get the values dynamically and datagrid columns dynamically…i.e., in the array how to get the values dynamically ?
Coould you please guide me how to do this?
Regards
Sireesha.
Hi,
The datagrid posted here is not editable. Can you throw some light on creating an editable datagrid connected with database.
Cheers!!!
Ujjwal B Soni
Ujjwal B Soni,
Only the second column (score) in the example’s data grid is editable.
Peter
Hi Peter,
If I use xml not ArrayCollection, how can I edit datagrid and save the change back to the xml source?
Many thanks.
Not sure if this is possible…You seen like the guy to ask…
I would like to build a datagrid dynamically with amounts cnts etc…like this..
oColumnDef = new DataGridColumn(); oColumnDef.headerText = "Amount"; oColumnDef.dataField = "S"+Storesdp.getItemAt(i).data+"_all_amt"; oColumnDef.width = 60; oColumnDef.sortable = true; oColumnDef.visible = true; oColumnDef.editable = false; oColumnDef.wordWrap = false; oColumnDef.labelFunction = amtLabelFunction; oColumnDef.setStyle("textAlign","right"); colArray.push(oColumnDef);Then have one column as a combobox…like this…
This works as expected…combo renderer I would like to change the dg values for that row based on the users selection (users can select All, 30, 60, 90, 120, 150, 180)
so in the changeHandler of the combo I have some code but cannot seem to figure out the correct syntax to make it work…I have attempted using the selectedIndex of datagrid…
I am not sure my method is correct as the dataprovider for the dg contains separate fields for all, 30, 60, 90 etc….
Perhaps I should use a repeater instead of datagrid so I would have more control and an my simple structure (renderers are a pain)…Thoughts? I am aware that this post may be difficult to interpret but I did not want to post to much code…as I do not assume others want to do all the work for me…I am just looking for a nudge in the right direction…
I was hoping to use a datagrid rather that repeater for performance reasons…Let mw know if you need other information or if anyone is aware of other resources that would help
Hi, does anyone know how to adapt Brent’s CellEditable for columns using labelFunction (not dataField) ?
thanks
Anyone else have issues where the scroll bar will fire off itemEdit events and it passes the last item you edited? So for example you’d click on the number in the example above and then when you’d scroll it would open the editor for the same element. For the life of me I can’t figure out why its doing that.
Okay sorry to double post, I just figure out what is making the scroll bar fire the events, I think its a flex bug. If you have selectable=false in the datagrid then i think it confuses some of the events and the scrollbars with execute them.
hello frnds,
could we make rounded corners of datagrid?
abhishekchess1@gmail.com
thx in advanced,
:)
Hello,
I have some problem events in datagrid flex 3.
The main goal is to create new row when user finish editing the cell and hits the enter key.
The problem is that for:
-click on new row with mouse
or
-hitting the enter key from keyboard
is the same event reason: “newRow”
I “ask” a google for the solution but without luck.
First I tried to add an event listener to KeyboardEvent.KEY_UP, and it is working for each key, except the ENTER (method for that listener is called after the editing).
Can you please help me how to distinguish mouse click on edit end and ENTER from keyboard.
Thanx in advance,
Ognjen
Hello everybody,
nobody has answered the question of bhargavi.
Can somebody please tell me how I can get the new value of an edited cell.
Thanks.
Hi ,
Need some help on Datagrid…
I created a Datagrid with some records (from salesforce.com) ,now i need a checkbox with every record .
When user clicks SAVE Button – at that time i want to pick the selected (SELECTED By Check BoX) records.Please guide me how can i achieve this
Thanks
Nikhil
You are the man peter! Thanks for the selectable tip for DataGridColumn.
I am trying to build a Flex Datagrid that reads xml that is generated by php. Than the user should be able to edit the datagrid, and save the data back to the same xml file. again with the help of php.
But when i try to get the new data from the datagrid by myDatagridsId.dataProvider -> i only get the original data.
How can i get the actual data, that has been edited ?
<!--csvdata>{objectToXML(dgUserRequest.data).toXMLString()}</csvdata--> {dgUserRequest.dataProvider} {keystring.text} {destring.text} {enstring.text}Ben, bhargavi,
the current edited data seems to be located in:
event.target.itemEditorInstance.text
hi
I have a data grid where one row of data is really long. I want to have a scroll bar option so that the data can be seen without increasing the width of the datagrid. I know it automatically allows for height but what can i do for width. I dont want my datagrid to look too big. And also can I group rows of data inside a datagrid, like for ex: can data from 3 rows be grouped in one row and then an expand button be placed. Please reply!
@vineet,
You can set a horizontal scroll policy for the DataGrid control that will allow for horizontal scrolling of the data (as well as support for a specific number of locked columns).
As for row grouping look at the AdvancedDataGrid control in Flex Builder Professional.
Peter
I have a dataGrid that is display only. The row id is listed in the grid and I need to make it possible for the user to select that cell for cutting and pasting. I have made the column editable but I’m afraid the user will accidentally alter the data and I need a way to make sure they don’t change the data. The id needs to remain as it is in the database because once the user has determined that the row data is all correct, they can select the row and update the “viewed” flag and the row id is how the database will be updated. If the row id has changed on the screen, the database will not updated.
How can I keep this column updatable but not allow the data to be changed?
@Jacey,
Take a look at my “About you” page: http://blog.flexexamples.com/about-you/
The first column, “Name”, isn’t editable. The second column, “Value”, is selectable but not editable. I believe that is what you were looking for (“possible for the user to select that cell for cutting and pasting… and I need a way to make sure they don’t change the data.”).
You can view the source at: http://blog.flexexamples.com/wp-content/uploads/Capabilities_test/bin/srcview/ and the trick was a custom item editor (I used a mx:TextArea control) where you set the
editableproperty tofalse. You could also possibly use an mx:Label control or mx:Text control and set theselectableproperty totrue(or something, I haven’t tested that).HTH,
Peter
Sorry, here is my code:
Sorry, I’ve pasted my code in here twice and it still won’t show up. I don’t know how to get my code to show.
You have to replace your < chars with < and your > chars with >.
Sorry, I used to have a giant disclaimer above the comments box that said that, but I must have lost that when I updated my WordPress theme last night.
Peter
Yes, thank you, this is exactly what I need. Unfortunately, I get an error that says “The element type ‘mx:columns’ must be terminated by the end-tag ”. The error is on the ” line (10th line of code). Any idea why?
Here is my code:
I’d verify that you have a </mx:columns> tag before the </mx:DataGrid> tag.
I didn’t know about the conversion so hopefully this will work. I have verified that I have the end-tags that I need. Can you see anything else wrong with my code? Thanks!
@Jacey,
Without seeing any code, I’m not sure what the issue is.
I’d try renaming the .MXML file to something with an .XML file extension and try opening it in Internet Explorer or Firefox and see if it shows any XML parsing errors.
Peter
Hi, i need some help.
in the itemEditBegin and itemEditEnd, of the data grid i catch the event, that cool. but it you change the text in the datagrid, the data in the itemEditBegin is the same of itemEditEnd, its like you never change the data.
example, lets say column 1 , row 1 has value 50. So in the itemEditBegin event the data has 50, so i change it to 60 and then focus out and the itemEditEnd come to action, so i consult the data and its still 50.
any can help me please ? i need the 60 .
Thx.
Solve it, its in focusOut.
Thx anyway.
Hey Peter, though unrelated to this post, you might consider adding a link to this tool http://blog.rubybestpractices.com:3000/code in your disclaimer. It’s specifically geared towards converting code to a HTML friendly format. Dropping a mail to the site owner saying that you are using his service would be appreciated.
Testing sample code:
Works!
-sanjay
Oops, sorry. The tool is http://www.htmlescape.net/htmlescape_tool.html
It ought to work now!
<mx:DataGrid dataProvider="{myDp}" width="80%" editable="true">
<mx:columns>
<mx:DataGridColumn headerText="First Name" itemRenderer="mx.controls.TextInput"
editorDataField="text" editable="true" dataField="name" />
<mx:DataGridColumn headerText="Second Name" itemRenderer="mx.controls.TextInput"
dataField="occupation" />
<mx:DataGridColumn headerText="Details" itemRenderer="my.HboxRenderer" rendererIsEditor="true" />
</mx:columns>
</mx:DataGrid>
Thank you very much for your original code. I was never able to paste my code here but I found out that my error was because I had a closing tag “/” in the DataGridColumn line that was immediately before the “ItemEditor” lines of code. Taking out the “/” solved the problem. Again, thank you. Jacey
Hi there,
I’m having trouble using the values in a data grid to modify a variable.
I have a datagrid with 2 columns: country, coffee, and tea. each column contains price values (price per pound) I would like to select coffee or tea from a dropdown menu, and use a vslider to increment how many pounds are selected. This should modify a variable for totalprice, which is a sata provider for a label. If the user changes the price per pound in the datagrid, that new value should be used to calculate the total price, as the user slides the vslider. An event listener on the vslider calculates the values “on the fly”.
The data source for the grid is an arraycollection containing: Commodity name, and price per pound, but I can’t get to the value for the price-per-pound variable to connect to the vslider for calculting the totalprice. How do I get that price-per-pound value from the array?
Any suggestions that anyone has would be welcome!!
OOPS – forget about the TEA. AND I forgot to paste the code!:
@thatbrock,
This is probably an over-simplification, but I just used data binding and gave all the control’s an
idproperty. That way I was able to set the Label control’s text to the ComboBox control’s selected item’stypeCoffeeattribute * the Slider control’s current value:Peter
I’d like to use the NumericStepper control as both an itemRenderer and an itemEditor in a DataGrid. However, I want the value of the stepSize property of the NumericStepper to change dynamically, using values taken from an Array. Can this be done? For example, the array containing the possible values for the stepSize property might look this this [1.01,1.05,1.1,1.2,1.3,1.5,2,2.5]. If the cell displays the value ‘1.5′ and the user clicks the ‘down’ button twice in the NumericStepper control, this should update the cell to display ‘1.3′ then ‘1.2′ respectively. Any suggestions how this could be achieved? Custom component or inline?
@Lee,
As far as I know that wouldn’t be possible (at least, not easily). The problem I had when trying something similar a year+ ago was that your step size would always be different depending on whether user was going to hit the up arrow or down arrow. If you have a finite set of values, I would probably just use a ComboBox instead. Or maybe even look at a custom skin to make the ComboBox look more like a numeric stepper.
Peter
Thanks Peter, I’ll look into the ComboBox approach.
Hello All,
I am working on a project where in datagrid i have checkbox and textinputs as itemrenderes. Now i dont know how can i bind that data back to my beans when user will select checkbox and enter some value in checkbox? As dataprovider for my datagrid is arraycollection which has beans . So each row in datagrid represent one bean from the arraycollection.
If anyone knows how can i bind this itemrenderer data back to my bean values please let me know.
Thanks in advance.
Hello Peter, your blog has helped me with several questions while learning Flex.
Do you (or a reader) know how to allow dragging a row to below the scroll (past the visible area) in an AdvancedDataGrid?
If my table is 50 rows, my AdvancedDataGrid is set to a height which shows 20 rows (user must scroll down to see the rest), and I want to drag row 1 to row 30 or 40… How is this possible?
Currently (with default settings) I can only drag-and-drop to a row that is visible on the page, not to a spot farther down, below the scroll.
Please reply! And thanks for any help! :)