Flex Friday Feature - Datagrid Component

Skill

Flex Friday Feature - Datagrid Component

Posted in:

Due to popular demand, we've got another flex tutorial here for you all. I am going to go over a Flex component that we get a lot of search traffic for, but I have not yet gone in depth about. The datagrid component is one of the most versatile and used UIComponents in the flex environment. After this tutorial you should have a good grasp on how to use the datagrid component and what can be done with it.

First off I will give a quick and dirty overview of the component. The DataGrid is a visual control that shows data in tabular form, it extends the functionality of List and farther down the line there is UIComponent, which all visual components extend. I should mention that you do not use the datagrid for a layout control, there is a grid layout control to use for this. If you want to learn some more about the cold hard details of DataGrid check out Adobe Livedocs Page.

So that brings us to a quick look at an empty DataGrid with no data attached. And as always, on any of the examples you can right click and view the source of the flex file.

Get Adobe Flash player

So lets make a couple observations about the default DataGrid (by default I mean this was added using the designer in Flex Builder). There doesn't seem to be anything special but you will notice you can drag the columns around to order them anyway you want. That functionality is built into the DataGrid object.

So what's the code behind this? You can see below that this application just has a couple basic things in it. We add a panel and set the title. The <mx:DataGrid> comes next and we set a couple attributes that are typical to ui elements: x, y, height and width. Now inside our DataGrid we add a <mx:columns> tag to say that we are now going to add our column definitions. Inside this tag we add a couple <mx:DataGridColumn> tags and each one of these defines one column in our grid. They have two main attributes (properties) we define: headerText which is the name that is going to appear at the top of the column, and the dataField which tells the column what field in the data from our data provider to use when displaying information (we will be taking a look at the data provider later). Then we just close all the open tags, and that is all there is to our first example.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
   width="435" height="216" viewSourceURL="../files/DataGridExampleUno.mxml">
  <mx:Panel x="0" y="0" width="435" height="216"
     layout="absolute" title="Empty Default Datagrid">
    <mx:DataGrid x="0" y="0" width="415" height="176">
      <mx:columns>
        <mx:DataGridColumn headerText="Column 1" dataField="col1"/>
        <mx:DataGridColumn headerText="Column 2" dataField="col2"/>
        <mx:DataGridColumn headerText="Column 3" dataField="col3"/>
      </mx:columns>
    </mx:DataGrid>
  </mx:Panel>
</mx:Application>

Now lets start adding some data to our DataGrid. To do this we are going to use a data provider: <mx:dataProvider>. This tag is going to go inside our dataGrid tag to let flex know we are going to explicitly define the dataProvider property of the DataGrid. Inside the data provider tag we simply add a few objects with properties that match the dataField names defined in the columns. In this example our dataField names are "name", "creator", and "publisher". After those objects we close our data provider tag and add our columns like the last example with slightly more descriptive headerText and dataFields properties . You will also notice that we added a property to our <mx:dataGrid> tag to limit the number of rows (rowCount). Right below is the application this creates, followed by the actual code.

Get Adobe Flash player

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
   width="379" height="156" viewSourceURL="../files/DataGridExampleDos.mxml" >
  <mx:Panel x="0" y="0" width="379" height="156"
     layout="absolute" title="DataGrid - Simple DataProvider">
    <mx:DataGrid x="0" y="0" height="116" width="359"
     rowCount="4">
      <mx:dataProvider>
        <mx:Object name="World of Warcraft" creator="Blizzard" publisher="Blizzard" />
        <mx:Object name="Halo" creator="Bungie" publisher="Microsoft" />
        <mx:Object name="Gears of War" creator="Epic" publisher="Microsoft" />
      </mx:dataProvider>
      <mx:columns>
        <mx:DataGridColumn headerText="Game Name" dataField="name"/>
        <mx:DataGridColumn headerText="Creator" dataField="creator"/>
        <mx:DataGridColumn headerText="Publisher" dataField="publisher"/>
      </mx:columns>
    </mx:DataGrid>
  </mx:Panel>
</mx:Application>

That is the most basic way to put data in the DataGrid but is not very useful if your data isn't completely static. Fortunately, that is by no means the only way to hook in data. Lets look at another way to provide data to our DataGrid, binding an ArrayCollection to the dataProvider property of our DataGrid. This is done inside the <mx:DataGrid> tag, where we set the dataProvider property to "{gamesData}" - the name of our bindable ArrayCollection (for more on Bindable check out this post). Now the information in our arrayCollection will show up in our datagrid just like the last example, and if the information in that array happens to be the same as the static data above, the two datagrids will look identical. But this time we have a variable that we can change dynamically. And thats how we get the code below:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
   width="379" height="156" viewSourceURL="../files/DataGridExampleTres.mxml" >
  <mx:Script>
   <![CDATA[
     import mx.collections.ArrayCollection;
     
     [Bindable]
     private var gamesData:ArrayCollection;
   ]]>
 </mx:Script>
  <mx:Panel x="0" y="0" width="379" height="156"
     layout="absolute" title="DataGrid - Simple DataProvider">
    <mx:DataGrid x="0" y="0" height="116" width="359"
       rowCount="4" dataProvider="{gamesData}">
      <mx:columns>
        <mx:DataGridColumn headerText="Game Name" dataField="name"/>
        <mx:DataGridColumn headerText="Creator" dataField="creator"/>
        <mx:DataGridColumn headerText="Publisher" dataField="publisher"/>
      </mx:columns>
    </mx:DataGrid>
  </mx:Panel>
</mx:Application>

But when you run the code you notice there is no data in the datagrid, due to the fact that we have not initialized it yet. We can do this using an event on the datagrid component. The event we are going to use is the creationComplete event, which is dispatched once after the control is done being built and drawn. So to hook in to this event set it equal to "{initDataGridData()}", which tells flex to call our actionscript function initDataGridData when the event is fired. Now in this function we set our gamesData to a new ArrayCollection and add a couple items to our ArrayCollection. The code in the first block below gets added to our <mx:Script> tag and the code in the second block is our new <mx:DataGrid> opening tag.

private function initDataGridData():void
{
  gamesData = new ArrayCollection();
  gamesData.addItem({name: "World of Warcraft",
      creator: "Blizzard", publisher: "Blizzard"});
  gamesData.addItem({name: "Halo",
      creator: "Bungie", publisher: "Microsoft"});


  gamesData.addItem({name: "Gears of War",
      creator: "Epic", publisher: "Microsoft"});
}

<mx:DataGrid x="0" y="0" height="116" width="359" rowCount="4"
   dataProvider="{gamesData}" creationComplete="{initDataGridData()}">

And here is what that adding that new code creates:

Get Adobe Flash player

Another use of the data provider property is that we can change what object is hooked to it on the fly. To do this we won't be using the dataProvider property in our <mx:DataGrid> tag at all. We are going to assign something to the property in actionscript. In the example below, pressing the button "Change Data" will populate the grid with a completely different array of data.

Get Adobe Flash player

To do this though we need a way to identify our DataGrid in actionscript, which we do by setting the id property on the DataGrid (which in this case we will set to "dgGames"). The next thing we do is use the same tactic as the last example to initialize our data but this time we initialize two ArrayCollections, the two sets of data we will be displaying in the grid. And at the end of the actionscript function we do the very important step of setting the dataProvider on our dgGames. Here we set the dataProvider to our first ArrayCollection gamesDataA. So now we are where we were in the last example (we can show a DataGrid with our data from gamesDataA) but with a slight difference - we didn't actually bind the data. The code to do this is below:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
   width="473" height="200" viewSourceURL="../files/DataGridExampleQuatro.mxml" >
  <mx:Script>
   <![CDATA[
     import mx.collections.ArrayCollection;
     
     private var gamesDataA:ArrayCollection;
     private var gamesDataB:ArrayCollection;
     
     private function initDataGridData():void
     {
       gamesDataA = new ArrayCollection();
       gamesDataA.addItem({name: "World of Warcraft",
           creator: "Blizzard", publisher: "Blizzard"});
       gamesDataA.addItem({name: "Halo",
           creator: "Bungie", publisher: "Microsoft"});
       gamesDataA.addItem({name: "Gears of War",
           creator: "Epic", publisher: "Microsoft"});
         
       gamesDataB = new ArrayCollection();
       gamesDataB.addItem({name: "Everquest",
           creator: "Verant Interactive", publisher: "Sony Online Entertainment"});
       gamesDataB.addItem({name: "City of Heroes",
           creator: "Cryptic Studios", publisher: "NCSoft"});
       gamesDataB.addItem({name: "Doom",
           creator: "id Software", publisher: "id Software"});
       
       gdGames.dataProvider = gamesDataA;
     }
   ]]>
 </mx:Script>
  <mx:Panel x="0" y="0" width="473" height="200"
     layout="absolute" title="DataGrid - Changing Data Provider">
    <mx:DataGrid id="gdGames" x="10" y="10" height="106" width="433"
     rowCount="4" creationComplete="{initDataGridData()}">
      <mx:columns>
        <mx:DataGridColumn headerText="Game Name" dataField="name" width="115"/>
        <mx:DataGridColumn headerText="Creator" dataField="creator"/>
        <mx:DataGridColumn headerText="Publisher" dataField="publisher"/>
      </mx:columns>
    </mx:DataGrid>
  </mx:Panel>
</mx:Application>

It is also a good time to note a property which I set in the DataGridColumn for "name", I explicitly set the width to 115 pixels so that the creator and publisher columns would have more room because of names like "Sony Online Entertainment". But other than that this isn't anything too special - all we did is set the dataProvider property outside of the DataGrid tag. But to make it more interesting lets add a button to our application and add a actionscript function to the click event. Here we call the function changeGameData. Below is the code to add to your panel, this will go right below the <mx:DataGrid> tag.

<mx:Button x="10" y="124" label="Change Data" id="butChangeData"
   click="{changeGameData()}"/>

The function will check to see if dgGames.dataProvider is equal to gamesDataA and if it is we set the dataProvider equal to our other ArrayCollection, gamesDataB. Otherwise we set the dataProvider back equal to gamesDataA. This code will go into the <mx:Script> tag. And this completes the current example - if you'd like to see the full source, you can scroll back up and choose "View Source" from its right click menu.

private function changeGameData():void
{
  if(gdGames.dataProvider == gamesDataA)
  {
    gdGames.dataProvider = gamesDataB;
  }
  else
  {
    gdGames.dataProvider = gamesDataA;
  }
}

In the final example of this tutorial I am going to show a few different things that can be done using the DataGrid component. I will show how to get information about selected rows (single and multiple) and also how to bind the information in your datagrid back to a variable. But getting the information back from the DataGrid isn't all that useful unless we are able to edit that information on the grid, so we are going to cover that as well. To get an idea of what I am talking about you can play with the example we are going to create right below. In this example there are two datagrids - the top one holds all the game data we have and the bottom one shows the data for whatever we have selected in the top grid. Also on the top you you can edit the various fields and changes will be automatically saved. You can also select multiple games by the standard Ctrl or Shift Clicking on the rows. On the bottom grid, you can only select one row at a time, and whatever is selected is also displayed in labels below the grid.

Get Adobe Flash player

And now to get into the code. The first thing to do is to set up the interface, and since the interface is not particularly complex, the code should be self-explanatory. We have a panel which takes up the entire application, two datagrids (and on both we limit the width of the name column), and six labels (three for the static text and three which we are going to update). Now anything that we are going to refer to or change needs to have an id property: the datagrids and the changing labels. And all this results in the code below:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
   width="457" height="502" viewSourceURL="../files/DataGridExampleCinco.mxml">
  <mx:Panel x="0" y="0" width="457" height="502" layout="absolute"
     title="DataGrid - Selection, Editing, and Binding... Oh My!">
    <mx:DataGrid id="dgAllGames" x="10" y="36" width="417" height="173">
      <mx:columns>
        <mx:DataGridColumn headerText="Game Name" dataField="name" width="115"/>
        <mx:DataGridColumn headerText="Creator" dataField="creator"/>
        <mx:DataGridColumn headerText="Publisher" dataField="publisher"/>
      </mx:columns>
    </mx:DataGrid>
    <mx:Label x="10" y="10" text="All our data"/>
    <mx:DataGrid id="dgSelectedGames" x="10" y="243" width="417" height="110">
      <mx:columns>
        <mx:DataGridColumn headerText="Game Name" dataField="name" width="115"/>
        <mx:DataGridColumn headerText="Creator" dataField="creator"/>
        <mx:DataGridColumn headerText="Publisher" dataField="publisher"/>
      </mx:columns>
    </mx:DataGrid>
    <mx:Label x="10" y="217" text="Selected Data"/>
    <mx:Label x="10" y="373" text="Game Name:"/>
    <mx:Label x="10" y="399" text="Creator:"/>
    <mx:Label x="10" y="425" text="Publisher:"/>
    <mx:Label x="97" y="373" id="lblGameName" />
    <mx:Label x="97" y="399" id="lblGameCreator" />
    <mx:Label x="97" y="425" id="lblGamePublisher" />
  </mx:Panel>
</mx:Application>

Now lets start by hooking the data for the top grid. We do this using a [Bindable] ArrayCollection named allGames like earlier in the tutorial. And we set the initialized data by adding a function, initDGAllGames to the creationComplete event for the top DataGrid. So now we have some script code which is going to go right below our <mx:Application> tag.

<mx:Script>
 <![CDATA[
   import mx.collections.ArrayCollection;
   
   [Bindable]
   private var allGames:ArrayCollection;
   
   private function initDGAllGames():void
   {
     allGames = new ArrayCollection();
     allGames.addItem({name: "World of Warcraft",
         creator: "Blizzard", publisher: "Blizzard"});
     allGames.addItem({name: "Halo",
         creator: "Bungie", publisher: "Microsoft"});
     allGames.addItem({name: "Gears of War",
         creator: "Epic", publisher: "Microsoft"});
     allGames.addItem({name: "Everquest",
         creator: "Verant Interactive", publisher: "Sony Online Entertainment"});
     allGames.addItem({name: "City of Heroes",
         creator: "Cryptic Studios", publisher: "NCSoft"});
     allGames.addItem({name: "Doom",
         creator: "id Software", publisher: "id Software"});
     allGames.addItem({name: "Guild Wars",
         creator: "Arena Net", publisher: "NCSoft"});
     allGames.addItem({name: "F.E.A.R.",
         creator: "Monolith Productions", publisher: "Vivendi"});
     allGames.addItem({name: "Wii Sports",
         creator: "Nintendo", publisher: "Nintendo"});
   }
 ]]>
</mx:Script>

The opening tag of our top DataGrid (which is named dgAllGames) now needs the dataProvider property set to our allGames ArrayCollection and a creationComplete event calling initDGAllGames(). This results in the following tag:

<mx:DataGrid id="dgAllGames" x="10" y="36" width="417" height="173"
 creationComplete="{initDGAllGames()}" dataProvider="{allGames}">

All of that we have done in previous examples, but now we are going to make the top grid editable. All we have to do to enable that is set the editable property in the DataGrid tag to true. The opening tag for dgAllGames should now look like this:

<mx:DataGrid id="dgAllGames" x="10" y="36" width="417" height="173"
   editable="true" creationComplete="{initDGAllGames()}" dataProvider="{allGames}">

But this does not cause any changes to the data in the grid to be saved - in order to do that we need to add a <mx:Binding> tag below our closing script tag. This source property in this binding tag will contain dgAllGames.dataProvider as ArrayCollection. What that means is that we are going to use the dataProvider data from dgAllGames as the data source, but we will treat it as an ArrayCollection. The destination property will be the original allGames ArrayCollection. So now our data is being saved back into the ArrayCollection. The binding code is below:

<mx:Binding source="dgAllGames.dataProvider as ArrayCollection"
   destination="allGames" />

Now we have a DataGrid which can display our data and update our data. One more thing we want to do with our top GataGrid is allow multiple rows to be selected at once, which is again just another property in our DataGrid tag. So we just set the allowMultipleSelection property to true and now we have ability to Ctrl or Shift Click multiple items. That should be it for the dgAllGames tag, which now looks like this:

<mx:DataGrid id="dgAllGames" x="10" y="36" width="417" height="173"
   editable="true" allowMultipleSelection="true"
   creationComplete="{initDGAllGames()}" dataProvider="{allGames}">

But whats the point of selecting items, if you can't tell what has been selected? An easy way to solve this is to bind the currently selected items to an array. So in our script code we add a [Bindable] array for our currently selected items. This means the following code gets added in our <mx:Script> tag.

[Bindable]
private var selectedGames:Array;

And we bind to this array using another binding tag just under our allGames binding. We set the source equal to dgAllGames.selectedItems - which is a property of the DataGrid object which returns an array of the currently selected items. Our destination is just going to be our new array selectedGames. This new binding tag is below:

<mx:Binding source="dgAllGames.selectedItems" destination="selectedGames" />

Just a couple things left to do now. First we will bind our selectedGames array to our dataProvider for our second datagrid, which means that whatever is selected in the first DataGrid gets displayed in the second. We also add an event hook to the second DataGrid's change event. A DataGrid fires the change event whenever its selectedIndex or selectedItem changes. We are going to use this event to update our labels. So the opening tag to our second DataGrid component, dgSelectedGames, now looks like the following code:

<mx:DataGrid id="dgSelectedGames" x="10" y="243" width="417" height="110"
 change="{selectedItemChanged()}" dataProvider="{selectedGames}">

All that is left now is to add the function referenced by the change event hook of the second DataGrid. This function (selectedItemChanged()) goes inside our script tag, and will be in charge of updating the three labels at the bottom of the example. What we do in here is set the text of our labels to the contents the selected item in our dgSelectedGames DataGrid. We can get to our selected item using the property dgSelectedGames.selectedItem and then we can simply reference the name, creator, and publisher as properties of the selectedItem object. The following code goes inside our <mx:Script> tag and will finish off our example.

private function selectedItemChanged():void
{
  lblGameName.text = dgSelectedGames.selectedItem.name;
  lblGameCreator.text = dgSelectedGames.selectedItem.creator;
  lblGamePublisher.text = dgSelectedGames.selectedItem.publisher;
}

And when you put all of this together, it results in the full source code for this example:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
   width="457" height="502" viewSourceURL="../files/DataGridExampleCinco.mxml">
  <mx:Script>
   <![CDATA[
     import mx.collections.ArrayCollection;
     
     [Bindable]
     private var allGames:ArrayCollection;
     
     [Bindable]
     private var selectedGames:Array;
     
     private function initDGAllGames():void
     {
       allGames = new ArrayCollection();
       allGames.addItem({name: "World of Warcraft",
         creator: "Blizzard", publisher: "Blizzard"});
       allGames.addItem({name: "Halo",
         creator: "Bungie", publisher: "Microsoft"});
       allGames.addItem({name: "Gears of War",
         creator: "Epic", publisher: "Microsoft"});
       allGames.addItem({name: "Everquest",
         creator: "Verant Interactive", publisher: "Sony Online Entertainment"});
       allGames.addItem({name: "City of Heroes",
         creator: "Cryptic Studios", publisher: "NCSoft"});
       allGames.addItem({name: "Doom",
         creator: "id Software", publisher: "id Software"});
       allGames.addItem({name: "Guild Wars",
         creator: "Arena Net", publisher: "NCSoft"});
       allGames.addItem({name: "F.E.A.R.",
         creator: "Monolith Productions", publisher: "Vivendi"});
       allGames.addItem({name: "Wii Sports",
         creator: "Nintendo", publisher: "Nintendo"});
     }
     
     private function selectedItemChanged():void
     {
       lblGameName.text = dgSelectedGames.selectedItem.name;
       lblGameCreator.text = dgSelectedGames.selectedItem.creator;
       lblGamePublisher.text = dgSelectedGames.selectedItem.publisher;
     }
   ]]>
 </mx:Script>
  <mx:Binding source="dgAllGames.dataProvider as ArrayCollection"
     destination="allGames" />
  <mx:Binding source="dgAllGames.selectedItems" destination="selectedGames" />
  <mx:Panel x="0" y="0" width="457" height="502" layout="absolute"
     title="DataGrid - Selection, Editing, and Binding... Oh My!">
    <mx:DataGrid id="dgAllGames" x="10" y="36" width="417" height="173"
       editable="true" allowMultipleSelection="true"
       creationComplete="{initDGAllGames()}" dataProvider="{allGames}">
      <mx:columns>
        <mx:DataGridColumn headerText="Game Name" dataField="name" width="115"/>
        <mx:DataGridColumn headerText="Creator" dataField="creator"/>
        <mx:DataGridColumn headerText="Publisher" dataField="publisher"/>
      </mx:columns>
    </mx:DataGrid>
    <mx:Label x="10" y="10" text="All our data"/>
    <mx:DataGrid id="dgSelectedGames" x="10" y="243" width="417" height="110"
       change="{selectedItemChanged()}" dataProvider="{selectedGames}">
      <mx:columns>
        <mx:DataGridColumn headerText="Game Name" dataField="name" width="115"/>
        <mx:DataGridColumn headerText="Creator" dataField="creator"/>
        <mx:DataGridColumn headerText="Publisher" dataField="publisher"/>
      </mx:columns>
    </mx:DataGrid>
    <mx:Label x="10" y="217" text="Selected Data"/>
    <mx:Label x="10" y="373" text="Game Name:"/>
    <mx:Label x="10" y="399" text="Creator:"/>
    <mx:Label x="10" y="425" text="Publisher:"/>
    <mx:Label x="97" y="373" id="lblGameName" />
    <mx:Label x="97" y="399" id="lblGameCreator" />
    <mx:Label x="97" y="425" id="lblGamePublisher" />
  </mx:Panel>
</mx:Application>

Hopefully this tutorial gave you a give overview of what the DataGrid component can do and what it can be used for. Look for a tutorial on advanced DataGrid techniques in the future, and remember that the examples here are not always done the best/fastest way, but are done in ways that show off certain features of the DataGrid component. If you have any questions about the examples or DataGrid in general feel free to leave a comment.

Paulo Jorge Dias
07/30/2007 - 05:25

Hi,
Thanks for your datagrid tutorial. It’s very instructive.
I am trying Flex since one month or so, and one think that annoyed me is the fact that don’t have the same behavior as , regarding the bi-directional databinding. In forms you can bind or in or out databind but not both as it is on .
Am I wrong because of little time playing with Flex?
Best regards,
Paulo Jorge Dias

reply

Paulo Jorge Dias
07/30/2007 - 05:28

Hi,
On my last post I missed some very important words. Here is again the complete text.
Thanks for your datagrid tutorial. It’s very instructive.
I am trying Flex since one month or so, and one think that annoyed me is the fact that form don’t have the same behavior as datagrid, regarding the bi-directional databinding. In forms you can bind or in or out databind but not both as it is on datagrid.
Am I wrong because of little time playing with Flex?
Best regards,
Paulo Jorge Dias

reply

The Fattest
07/30/2007 - 07:37

Well you are correct in that you can't bind the data both ways with one single call. But you can bind the data in by just binding it to the dataProvider. And you can bind it out using the mx:Binding tag. Now both of these can be used on the same DataGrid, and as a matter of fact you can bind the data out to as many variables as you want using multiple mx:Binding tags. So yes you can have multi-directional binding but it doesn't take the form of a single call.

reply

Nate Rock
07/31/2007 - 11:05

Awesome basic introduction to the DataGrid component! Going to recommend this to my buddies who are learning Flex =)

reply

Luke
09/30/2007 - 18:11

Hi. This is a good tutorial, but do you know how to add a DataProvider to a DataGrid that was created through Actionscript? I've tried everything and I receive a null Object reference error.

reply

The Fattest
09/30/2007 - 21:02

Yeah there is an example of this in the code of an earlier tutorial.

reply

Wolf
10/03/2007 - 20:42

Luke, the dataProvider for the data grid can be an arrayCollection, which is x number of of associative arrays.
In your script, declare a var of thype Array Collection -

[Bindable] public var idCollection:ArrayCollection=new(ArrayCollection);

If you want to fill your data grid with data collected from a form, you can do something like this:

var tempAssArr:Object = {idType:idTy, issuer:issuer.text,
    issueDate:issueDate.text, expDate:expDate.text, dob:dob.text,
    filePath:filePath.text, notes:notes.text};
idCollection.addItem(tempAssArr);

The key here is pushing an associative array into your dataCollection, and setting the data provider of your dataGrid to that ArrayCollection object.

reply

Jehanzeb
10/01/2007 - 01:55

Hello,

There is one short-coming in the example. The second grid does not preserve the user changes.

Let me explain it with a scenario.

1. Select few item from the first grid, that is, dgAllGames.

2. Click on "Game Name" column header of second grid, dgSelectedGames. It will sort the data in the grid.

3. Now click on the rows of dgAllGames grid. It will rebind the data in dgSelectedGames grid. Because of that dgSelectedGames grid lost all the customization (sorting on the basis of "Game Name" column) and restore its default settings.

What I want to know is there any way a grid can preserve the user changes during data binding?

Regards,
Jehanzeb

reply

Tariq
10/09/2007 - 14:50

This was an amazing tutorial, I just wish you taught how to load the data from a mysql database using PHP.

reply

The Fattest
10/09/2007 - 16:16

Tariq, I do cover that, just not in this tutorial. Check out this tutorial and this one.

reply

Buddy
01/22/2008 - 11:04

Can you help me with an example that shows how I could add a new row to the datagrid in Flex itself. I saw your example using Javascript and Flex, but I want a Flex only example.

Thanks in advance !!

reply

Swaminathan
02/06/2008 - 22:54

hi, this is very useful... thank you very much... Keep rocking...

reply

Kinny
02/12/2008 - 02:24

How can i display data in a datagrid from a xml file?
I tried dataprovider but it displays nothing :(

reply

Vijay
02/13/2008 - 03:29

Hi,

This is very nice, but I want the same thing from an Access DB. How do you do that ?, I have a working app. on the web, and I wanted a Flex Interface to it.

Can you point me in the right direction ?

reply

Sandeep Hooda
03/26/2008 - 23:26

Hi,
Thanks for the very useful information. It helped me a lot in by application that used data grid.

Regards
Sandeep Hooda

reply

Vasu
04/02/2008 - 00:30

Awesome tutorial....perfect pace...thanks a lot...keep rockin...

reply

Ali
04/16/2008 - 02:47

it is an extremely useful tutorial. helped me alot.
keep doing good job...

reply

Bill
05/04/2008 - 06:29

Great Example. Exactly what I was looking for.

Thanks a bunch.

reply

Deep
05/16/2008 - 05:27

Excellently Explained.My problem is that i have one array collection called msgdata.

I have a data grid with id "grid".

I can delete the selected rows by
msgData.removeItemAt(grid.selectedIndex); The rows get deleted alright.but the next time i load the project the data shows again.can we by any chance update the array collection after deleting the rows.Mine is a static array collection....

reply

The Fattest
05/16/2008 - 08:19

Deep, Do mean when you reload the page the data will again be there? If this is the case you need to store the data somewhere outside the application. The application will have no memory from one start up to the next.

reply

Deep
05/19/2008 - 05:59

thanks for the reply..no i want the data not to be present the next time..means the rows i delete should not be present the next time i load the page..but after i delete the rows and again load the page next time the data shows again..is it due to the fact that i m using array collection....can we can update the array collection also....

reply

The Fattest
05/19/2008 - 08:24

Deep, this is along the same lines as storing new data from page load to page load. You have to have something storing the data outside of Flex. There is no way to keep knowledge of that data inside Flex, this most likely means a database or some kind of cookie setup.

reply

Deep
05/19/2008 - 21:44

Thanks again for the reply...I m getting your point...it will be more helpful if i maintain a database and get the data from there so that i can modify them....

reply

The Fattest
05/20/2008 - 12:02

Deep, yeah absolutely.

reply

Prajakta
05/23/2008 - 09:47

will u help to write a function so that no two city name of a city table in a datagrid should not be same

reply

Vinitha
06/10/2008 - 01:14

Hi, Your samples are simple and clear. Thanks.

Can you help me in showing ellipses in the datagrid column?

Thanks in advance.

reply

Shikha
07/08/2008 - 00:11

ur examples helps alot.........

thanks n keep it up!

-cheers
Shikha

reply

Nico
07/16/2008 - 12:25

Hi,

great stuff.

i load data from an xml file, like this:

16-07-2008
Username
Subject
false

what i want is a row to have a different color when read=true instead of false.

is this possible with a datagrid in flex?

Best regards,
Nico

reply

Joe
07/22/2008 - 03:48

I´m going crazy with this one. I´ve got a datagrid being populated by an array loaded from an external file. When I load, the whole file gets published on every column.

Heres another one, trying to populate from a variable binding to a dataField but nothing is being published.

Please HELP ME!!!

reply

The Fattest
07/22/2008 - 12:54

joe, I am interested in seeing the datagrid code you are using. you can post it here in a comment or send it to us in an email. I would like to help just need a few more details.

reply

DenisPat
07/22/2008 - 09:49

Would you know how to reset the default size when the dataProvider is updated? (eg: when the number of recording changes, the datagrid expands in the remaining avalaible space since it cant display the whole list)

reply

Hazem
07/30/2008 - 04:31

Thanks for a great dataGrid 101 introduction.

I am working on datagrid that populates records from a database utilizing AMFPHP framework; everything is working ok.

My problem actually got to do with itemrenderers OR itemeditors; and its as follows:

I want to capture the data entered into itemeditor, and update my database accordingly;

what I am trying to do is to submit the datagrid dataprovider to PHP to do the update process on the database records; problem is that whenever i capture the datagrid dataprovider to send it; its not the UPDATED ONE!!

I'll summarize the whole issue by asking:

1. doesn't a binded DATA property of an itemeditor directly updates the data on teh data provider of the dataGrid ??

2. Does this has to do with BINDING?

3. or ist got to do with the SETTER GETTER overriding criteria ???

I am sorry for this long post :)

reply

The Fattest
07/30/2008 - 09:01

Are you sending the actual dataprovider of the DataGrid or are you sending the source the original collection that you used for the binding? The reason I ask is because only the dataprovider property on the datagrid will be updated unless you have a binding tag to bind the datagrid back to the collection. You can check out Binding Tutorial Part 1 for some more information.

reply

Hazem
08/01/2008 - 03:39

Well, yup I had that in mind, which is sending the actual dataprovider (the one to which the datagrid is hooked), as it should be the dynamic one that gets upadated by the EDITED DATA property of the ITEMEDITOR.

I'll read over the biding tutorial to check where I'm being wrong; and I shall keep you posted.

Many thanks.

reply

The Fattest
07/30/2008 - 09:16

Ok here is a new tutorial with some of the new datagrid features.

reply

Damir
08/11/2008 - 16:59

Hi,

IN order to specify table structure, the are listed. Is there a way to load a pre-defined table structure from a file or web-service?

Thanks.

reply

The Fattest
08/11/2008 - 18:24

damir, you would have to build a way to do this on your own but I mean you should be able pull in a definition from a file and create the table based on that at runtime.

reply

Shreepad Patankar
08/27/2008 - 04:28

my question is How can we make this code change so that user can use this grid with out mouse and blind user can also navigate through the same ?

reply

Napolux
10/06/2008 - 08:48

Amazing post, thanks a lot!

reply

MrChiBai
11/05/2008 - 15:32

+1 to amazing post. I'd buy you a beer if I could.

reply

Gawie
11/14/2008 - 23:55

First of all. Thank you very much for the very well thought out examples and easy to follow structure.

Two questions though:
One thing I find impractical is that you have to use the mouse for navigation for the arrow keys 'get stuck' inside the edit. Unless you change an edit, (up, down, home, end, pg up etc) navigation keys should still function as normal.

Also, what would you do to simulate a 'new record' with cancel capability e.g. when you press down after the last record it can add an 'empty row'. If you do not fill in any of the fields it is considered a cancel and the row is removed, otherwise it should be filled in full (or a permanent empty row at the top like M$ datagrids).

How would you change the example to make it complete.

Regards and Thanks again fro a very well composed article.
Gawie

reply

Alice
11/25/2008 - 08:15

This is a comprehensive article on the different types of things we can do with dataGrid. I have a question regarding your final section on your dataGrid. Is it possible that you could provide some resources or examples on how we could update all the records shown in the table at once instead of displaying selectedItem one by one?

reply

K L Reddy
12/05/2008 - 10:03

Hi,

This material is very usefull to the guys who want to know about flex data grid. I heartly thankfull to this guy,who presented this one.It is very usefull to my current web application also. , not only for me it is usefull any one who want to use Flex grid..

reply

JK
01/10/2009 - 05:35

very cool.

http://www.bintelligence.altervista.org/

reply

Deniz
05/09/2009 - 07:26

This great explanatory tutorial really helped me! Thanks a lot :)

reply

rayliner
05/29/2009 - 12:54

I'm trying to change the color of the header of a single column. Can someone post a sample of how to do this with, say, the enpty datgrid sample at the top of this thread? I've had a few peaople elsewhere tell me to 'just try this to add a....', and I obviously still did something wrong. Thanks

reply

keoki
10/09/2009 - 13:44

hello:

I am new to Flex.

I currently have two data grids, in to different views.

When one record is clicked on in the first data grid it calls a webservice that populates the second data grid.

My question is... What is the easiest way to have a Next and Previous button that will go to the next record in Data Grid 1 and reactivate the webservice which will repopulate Data Grid 2 with the relative information?

I have tried to do this in SQL and created a few more webservices. However, this doesn't do everything I'd like. There has to be a different way to go about this.

I'd also like the focus to be set to the next or previous record in Data Grid 1 when buttons are pressed on the view page of Data Grid 2.

Any help is appreciated...

Keoki

reply

flexicious
11/30/2009 - 01:20

Feel free to check out www.flexicious.com. It does a lot of stuff in addition to what's provided by Flex out of the box. Examples are Column level filtering, Server based paging and sorting, column footers, data copy paste, and a lot more!

reply

Manoj
12/22/2009 - 08:29

Hi all,
I am trying to design a flex application in which data inside the datagrid will move downside automatically.
Can anyone provide me the code sample?

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.

Sponsors