Creating an editable DataGrid control in Flex

by Peter deHaan on May 11, 2008

in DataGrid, DataGridColumn

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.

View MXML

<?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.

View MXML

<?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 }

1 Prashanth Samanth May 14, 2008 at 3:34 am

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

Reply

2 peterd May 14, 2008 at 8:23 am

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

Reply

3 vineet October 22, 2009 at 6:22 pm

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!

Reply

4 Brent May 21, 2008 at 9:24 am

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 !!!

Reply

5 Brent May 21, 2008 at 1:52 pm

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.

Reply

6 Prashanth Samanth May 26, 2008 at 11:56 pm

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

Reply

7 Prashanth Samanth May 27, 2008 at 12:16 am

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

Reply

8 peterd May 27, 2008 at 12:21 am

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

Reply

9 Prashanth Samanth May 27, 2008 at 3:58 am

Peterd,

I even want a Text input before the Browse, so that the User can directly type the path he want to upload…

PSamanth

Reply

10 Prashanth Samanth May 27, 2008 at 4:18 am

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

Reply

11 Brent May 28, 2008 at 1:41 pm

Yeah yeah check this out. Dig this, Johnson !!

Here’s your dataGrid code:

<mx:DataGridColumn headerText="Quantity" dataField="Quantity" textAlign="center" itemRenderer="path.to.your.view.EditableCellRenderer"
itemEditor="path.to.your.view.EditableCellEditor" />

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%.

Reply

12 Brent May 28, 2008 at 4:25 pm

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>

Reply

13 Alex C August 26, 2008 at 7:51 am

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.

Reply

14 bhargavi August 29, 2008 at 7:05 am

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.

Reply

15 SD.Plox September 3, 2008 at 9:03 am

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

Reply

16 peterd September 3, 2008 at 10:41 am

SD.Plox,

There may be easier/better ways, but you can definitely create a custom item renderer and set the selectable property to true, 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 selectable property 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

Reply

17 peterd September 3, 2008 at 10:56 am

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 editable property to false.

Reply

18 Stuart Ward September 4, 2008 at 11:44 am

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

Reply

19 Sireesha December 2, 2008 at 5:01 am

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.

Reply

20 Ujjwal B Soni January 18, 2009 at 8:49 am

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

Reply

21 Peter deHaan January 18, 2009 at 7:16 pm

Ujjwal B Soni,

Only the second column (score) in the example’s data grid is editable.

Peter

Reply

22 Scarlet sail January 18, 2009 at 10:31 pm

Hi Peter,

If I use xml not ArrayCollection, how can I edit datagrid and save the change back to the xml source?

Many thanks.

Reply

23 wpageiii February 17, 2009 at 12:36 pm

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…

oColumnDef = new DataGridColumn();
oColumnDef.headerText = "Age";
oColumnDef.width = 50;
oColumnDef.sortable = true;
oColumnDef.visible = true;
oColumnDef.editable = true;
oColumnDef.wordWrap = false;
oColumnDef.itemRenderer = new ClassFactory(BarometerView.comboboxrenderer);
oColumnDef.rendererIsEditor= true;
colArray.push(oColumnDef);

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

Reply

24 Nayk February 19, 2009 at 3:37 am

Hi, does anyone know how to adapt Brent’s CellEditable for columns using labelFunction (not dataField) ?
thanks

Reply

25 Bartimus March 10, 2009 at 2:13 pm

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.

Reply

26 Bartimus March 10, 2009 at 2:17 pm

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.

Reply

27 abhishek April 22, 2009 at 6:52 am

hello frnds,
could we make rounded corners of datagrid?
abhishekchess1@gmail.com
thx in advanced,
:)

Reply

28 ognjen July 7, 2009 at 8:33 am

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

Reply

29 ben July 30, 2009 at 12:57 am

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.

Reply

30 Nikhil August 19, 2009 at 5:57 am

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

Reply

31 Paul August 27, 2009 at 12:59 am

You are the man peter! Thanks for the selectable tip for DataGridColumn.

Reply

32 Bender October 8, 2009 at 6:40 am

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&gt;{objectToXML(dgUserRequest.data).toXMLString()}&lt;/csvdata-->
            {dgUserRequest.dataProvider}
            {keystring.text}
            {destring.text}
            {enstring.text}

Reply

33 Brian October 21, 2009 at 7:36 am

Ben, bhargavi,

the current edited data seems to be located in:

event.target.itemEditorInstance.text

Reply

34 vineet October 22, 2009 at 6:23 pm

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!

Reply

35 Peter deHaan October 22, 2009 at 6:30 pm

@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

Reply

36 Jacey October 29, 2009 at 2:52 pm

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?

Reply

37 Peter deHaan October 29, 2009 at 7:15 pm

@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 editable property to false. You could also possibly use an mx:Label control or mx:Text control and set the selectable property to true (or something, I haven’t tested that).

HTH,
Peter

Reply

38 Jacey October 30, 2009 at 1:50 pm

Sorry, here is my code:

39 Jacey October 30, 2009 at 3:03 pm

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.

40 Peter deHaan October 30, 2009 at 6:35 pm

You have to replace your < chars with &lt; and your > chars with &gt;.

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

41 Jacey October 30, 2009 at 10:26 am

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:

Reply

42 Peter deHaan October 30, 2009 at 2:57 pm

I’d verify that you have a </mx:columns> tag before the </mx:DataGrid> tag.

Reply

43 Jacey November 2, 2009 at 10:01 am

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!

44 Peter deHaan November 2, 2009 at 5:41 pm

@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

45 Rene R Ramirez S October 31, 2009 at 6:33 am

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.

Reply

46 Rene R Ramirez S October 31, 2009 at 7:11 am

Solve it, its in focusOut.

Thx anyway.

Reply

47 sanjayts November 2, 2009 at 3:05 am

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

Reply

48 sanjayts November 2, 2009 at 3:08 am

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>

Reply

49 Jacey November 3, 2009 at 1:44 pm

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

Reply

50 thatbrock November 5, 2009 at 2:52 pm

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!!

Reply

51 thatbrock November 5, 2009 at 4:08 pm

OOPS – forget about the TEA. AND I forgot to paste the code!:

Reply

52 thatbrock November 5, 2009 at 4:10 pm
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
 
    <mx:Script>
        <![CDATA[
            import mx.events.SliderEvent;
            import mx.collections.*;
            import mx.controls.sliderClasses.Slider;
 
            private var totalPrice:Number = 0;
            private var selectedPrice:Number = 0;
 
            [ Bindable]
            public var commodity:ArrayCollection = new ArrayCollection([
                    {country:"Colombia",typeCoffee:3.99},
                    {country:"Ethiopia",typeCoffee:7.99},
            ]);
 
            private function changeEvt(event) {
                selectedPrice = // ????  use the selected country to make the calculation
            }
 
            private function sliderChange(event:SliderEvent):void {    
                var currentSlider:Slider=Slider(event.currentTarget);
                totalPrice = currentSlider.value * selectedPrice;
                lblPrice.text=totalPrice.toString();
            }
        ]]>
    </mx:Script>
 
    <mx:DataGrid x="10" y="10" dataProvider="{commodity}" editable="true">
        <mx:columns>
            <mx:DataGridColumn headerText="Country" dataField="country"/>
            <mx:DataGridColumn headerText="Coffee" dataField="typeCoffee"/>
        </mx:columns>
    </mx:DataGrid>
 
    <mx:ComboBox x="42" y="364" close="changeEvt(event)" dataProvider="{commodity}" labelField="country" ></mx:ComboBox>
    <mx:VSlider x="179" y="224" id="sliderCoffee" liveDragging="true" change="sliderChange(event);"/>
    <mx:Label x="277" y="366" id="lblPrice" text="Price"/>
 
</mx:Application>

Reply

53 Peter deHaan November 5, 2009 at 6:01 pm

@thatbrock,

This is probably an over-simplification, but I just used data binding and gave all the control’s an id property. That way I was able to set the Label control’s text to the ComboBox control’s selected item’s typeCoffee attribute * the Slider control’s current value:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
 
    <mx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
 
            [Bindable]
            public var commodity:ArrayCollection = new ArrayCollection([
                {country:"Colombia", typeCoffee:3.99},
                {country:"Ethiopia", typeCoffee:7.99}
            ]);
        ]]>
    </mx:Script>
 
    <mx:Panel>
        <mx:DataGrid id="dGrid" dataProvider="{commodity}" editable="true" width="300">
            <mx:columns>
                <mx:DataGridColumn headerText="Country" dataField="country"/>
                <mx:DataGridColumn headerText="Coffee" dataField="typeCoffee"/>
            </mx:columns>
        </mx:DataGrid>
        <mx:ControlBar>
            <mx:ComboBox id="cBox" dataProvider="{commodity}" labelField="country" />
            <mx:HSlider id="sliderCoffee" liveDragging="true" width="100" />
            <mx:Label id="lblPrice" text="${(cBox.selectedItem.typeCoffee * sliderCoffee.value).toFixed(2)}" />
        </mx:ControlBar>
    </mx:Panel>
 
</mx:Application>

Peter

Reply

54 Lee November 9, 2009 at 8:21 am

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?

Reply

55 Peter deHaan November 9, 2009 at 8:40 am

@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

Reply

56 Lee November 9, 2009 at 9:06 am

Thanks Peter, I’ll look into the ComboBox approach.

57 USCTrojan December 2, 2009 at 9:18 am

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.

Reply

58 Richard of Norway March 16, 2010 at 7:21 am

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! :)

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: