[Gambas-user] Referencing a listbox in a list container...

Tobias Boege taboege at ...626...
Fri Jul 11 19:44:02 CEST 2014


On Fri, 11 Jul 2014, Stephen wrote:
>    I am trying to clear the contents of all list boxes contained within 
> a list container by passing the list container to a SUB. Something like 
> this (I know this is not correct but it gets the idea across);
> 
> SUB ClearLists(phListContainer AS ListContainer)
>           phListContainer.child[0].clear
> END
> 
> But the child[0] returns the properties and methods for the basic 
> control object which does not have Clear as an option.
> I need to be able to iterate through the children of the container, and 
> clear their contents.
> 

I think you are looking into the documentation ListContainer -> Children ->
_get()/_put() which tells you that the return value of

  ListContainer.Children[iIndex]

is of type Control which does not have a Clear() method.

As explained here[0], Gambas uses "virtual dispatching" for its objects.
This means that the type of variable/return value an objects lives in does
not matter when it comes to property access/method call. Instead, each
object keeps a reference to its true class attached to itself from which
property/method names are resolved into functions to call; and variable
types have merely the purpose to define what *kind* of object to expect.

So if you get a Control back, it can actually be a ListBox which is a
container and especially a Control. Just because its variable type is
Control, doesn't mean you cannot call methods of the ListBox the object
actually is. Only the IDE will not be able to tell you through its pop-ups
that a ListBox-specific method exists - because it cannot know what you are
dealing with at runtime.

OK, now we get to the next level because what I told you above is actually
not the entire truth. There are some operations which are too "obscure" to
the interpreter - that's at least what my understanding is, I have to
citable resource here - to be virtually dispatched. This includes whenever
you access a virtual object property like in

  ListBox.Children.Clear()

which you use to clear a ListBox. In this case, it helps to promote the
Control to a local ListBox variable. This is the complete code:

Public Sub ClearLists(hListContainer As ListContainer)
  Dim hControl As Control
  Dim hListBox As ListBox

  For Each hControl In hListContainer.Children
    If hControl Is ListBox Then
      hListBox = hControl
      hListBox.Children.Clear()
    Endif
  Next
End

Regards,
Tobi

[0] http://gambaswiki.org/wiki/doc/object-model

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




More information about the User mailing list