[Gambas-user] Get the object of a component by name.

Tobias Boege taboege at ...626...
Wed Feb 24 20:22:27 CET 2016


On Wed, 24 Feb 2016, Matias De lellis wrote:
> >It is a different>matter, though, if Firmata is a graphical control. Graphical controls always
> >have a name property and you can use a Form's Controls property to search a
> >control by name like this:
> >
> >  hMyFirmata = FMain.Controls["Firmata1"]
> >
> >Note again: this only works if you know the form (FMain in this case) where
> >you want to search your object and the object is a control.
> 
> 
> I thought it, but as inherited from SerialPort (Not UserControl) does not work..
> 
> I implemented this in the previous attached example, and prints all controls except virtuals.
> > Dim hControl As Control
> > Dim hForm As Form Then
> > If Me.Parent Is Form ' Always can iterate to find the Form..
> >   hForm = Me.Parent
> >   For Each hControl In hForm.Controls
> >     Debug hControl.name
> >   Next
> > Endif
> 
> May need to do inherit from UserControl but I have to add even more code to relate the UserControl parent with the child SerialPort properties and events..
> 

OK, then another, more self-contained way. You have a class Firmata which is
instantiable and you want to keep track of the instances, right? Then modify
Firmata.class like so:

  Static Private $cObjects As New Collection

  Static Public Sub _get(Name As String) As Firmata
    ' Search through registered objects
    Return $cObjects[Name]
  End

  Public Sub _new(Name As String)
    ' Register every newly created Firmata object
    $cObjects[Name] = Me
  End

There is a static Collection which records every newly created object. You
must now specify a name for each Firmata object on creation. Given a string
variable sName which contains a the name of an existing Firmata object you
can obtain the object simply as

  hMyFirmata = Firmata[sName]

The above code will give you circular reference errors and it does not
include a way to remove an instance from the Collection so that its refcount
drops to zero and the Firmata object can be deleted. I have not enough time
ATM to make a better example, but if you get the idea, I'm sure you can fix
the remaining issues.

Regards,
Tobi

-- 
"There's an old saying: Don't change anything... ever!" -- Mr. Monk




More information about the User mailing list