3 Replies Latest reply on Nov 28, 2010 1:51 AM by frank_zhang

    How to set the width of DataGridColumn dynamically?

    frank_zhang

      What I want to do is, load data from a text file and put into a DataGrid component, the fields of ech record in the text have fixed length, and are seperated by a space, like this:


      personal.txt

      50 Uvwxyz  Male    123456789
      60 Hijklmn  Male    67890123456789
      30 Abcdefg Male    123456789012345
      40 Opqrst   Female 987654321012345678
      

       

      the configuration file is column.xml:

      <dgcolumn>
           <personal>
                <len>20</len>
                <title>Name</title>
           </personal>
           <personal>
                <len>3</len>
                <title>Age</title>
           </personal>
           <personal>
                <len>6</len>
                <title>Sex</title>
           </personal>
           <personal>
                <len>20</len>
                <title>IdNumber</title>
           </personal>
      </dgcolumn>
      
      

       

      First I load the column.xml into an arrColumn, then read the personal.txt and seperate the record by the width( "len" in the xml file ), and put the seperated fields into another arrField, set the arrayFld as the dataProvider of a DataGrid, thus, the title can be showed as the headerText of the DataGrid and the data can be loaded correctly.

       

      private function handleComplete( event:Event ):void
      {
           var arrField:Array = new Array();
           var arrFile:Array = loader.data.split(/\n/);
      
           for( var i:int = 0; i < arrColumn.length; i ++ )
           {
                arrField[i] = convIcom( arrFile[i] );
           }
      
           adgFile.dataProvider = arrField;
           
           trace( "The data has successfully loaded" );
      }
      
      private function convIcom( strRecord:String ):Object
      {
           var key:String = null;
           var dataField:String = null;
           var offset:int = 0;
           var obj:Object = new Object();
           
           if( strRecord.length > 0 )
           {
                for( var i:int = 0; i < arrColumn.length; i ++ )
                {
                     dataField = strRecord.substr( offset, arrColumn[i].len );
                     key = arrColumn[i].title;
                     obj[key] = dataField;
                     offset += arrColumn[i].len + 1;
                }
           }
           
           return obj;
      }
      
      <mx:DataGrid x="10" y="100" width="400" id="dgFile" />
      

       

      The problem is, the width of the DataGridColumn is average, how to set the column width by the length of each field? I can calculate the rate of each field ( field / fields ), but I don't know how to change the property of the DataGridColumn.width.

       

      Thanks for helping.