3 Replies Latest reply on Oct 26, 2007 4:29 PM by ntsiii

    addChild Controls not Found!

    dan1123
      Hi,

      When I add a control to a container at runtime using addChild, it shows up on the screen. However, if I subsequently try to access the control using getChildByName or through the parent's property array, Flex can't seem to find it. Both methods work for accessing child controls added at design time. The following code generates a runtime error " testText not found on testapp and there is no default value."

      <mx:Script>
      <![CDATA[
      import mx.controls.Text;
      import mx.controls.Alert;

      public function init():void {
      var newField:Text = new Text()
      newField.text = "hello";
      newField.id = "testText";
      this.addChild(newField);
      Alert.show(this["testText"].text);
      }
      ]]>
      </mx:Script>
        • 1. Re: addChild Controls not Found!
          Pkeating
          try setting the 'name' attribute of newField as it is in package flash.display. Also, getChildByName will return a DisplayObjecy so you may need to cast it to Text

          public function init():void {
          var newField:Text = new Text()
          newField.text = "hello";
          newField.name = "testText";
          this.addChild(newField);
          var myField:Text = Text(getChildByName("testText"));
          trace(myField.text);
          }
          • 2. Re: addChild Controls not Found!
            dan1123 Level 1
            thanks - casting the getChildByName to Text made the difference!
            • 3. Re: addChild Controls not Found!
              ntsiii Level 3
              FYI, Adobe advises against depending on getChildByName.

              The suggested way to handle this situation is to maintain a list of references to components you instantiate with addChild. Something like this

              private var _oChildArray:Object = new Object; //instance/global var

              ...
              var newChild:UIComponent = new UIComponent;
              var sId:String = "someid";
              newChild.id = sId;
              oChildArray[sId] = newChild;
              myContainer.addChild(newChild)

              then later, access the component:
              var myComponent:UIComponent = oChildArray["someid"]

              Tracy