[Gambas-user] Adressing a self-made object

Tobias Boege taboege at ...626...
Thu Oct 24 15:22:01 CEST 2013


On Thu, 24 Oct 2013, Alain Baudrez wrote:
> Hello,
> 
> I have been trying to emulate the VB.NET listbox control with checkboxes. I
> use this code to create and display them in a scrollview:
> 
> [code]
> 
> ' Declare a  checkbox
> Private hCheckbox As CheckBox
> 
> ' Create instances ofthe checkbox and place them
> ' in the parent Scrollview called ScrollFunction
> '
> Private Sub FillScrollBox()
> 
>   Dim vPos As Integer = 1 ' Counter representing the nth item
> 
>   $rs = $db.Exec("SELECT *  FROM tblListFunctie")
> 
>   For Each $rs
>     hCheckbox = New CheckBox(ScrollFunction)
>     With hCheckbox
>       .x = 10
>       .y = (vPos - 1) * hCheckbox.Height + 5
>       .width = 150
>       .text = $rs!Function
>       .tag = $rs!ID
>     End With
>     Inc vPos
> 
>   Next
> End
> [/code]
> 
> All checkboxes are displayed in the ScrollView, but how do I address any of
> those checkboxes?
> 
> I need to be able to set/read the value of those checkboxes. I tried :
> 
>    hCheckbox = New CheckBox(ScrollFunction) AS "chkScroll" & vPos
> 
> but I cannot address the object chkScroll1
> 
>   chkScroll1.value = TRUE
>  returns an 'Unknown Identifier'
> 

The "chkScroll" & vPos gives the *event name* of the object. It does *not*
create a variable for you holding a reference to the object!

> Moreover, I don't know how many checkboxes I created. Yes, I could keep
> track of the variable vPos and use that, but is there a generic way to loop
> through only the checkboxes in their parent, namely the Scrollview?
> 
> Any tips are welcome

As Bruce said, you can use Last in an event of any of these CheckBoxes. But
if you want to do this, you will have to give the same event name to all the
CheckBoxes (since you don't know how many CheckBoxes you have, you can't -
and generally shouldn't - create an event handler for each CheckBox with
identical code for all of the CheckBoxes).

This only works when you want to access the data when an event occurs.

There are two different approaches:

1) Use an array. After you created the CheckBox, push it into an array which
   you can freely index later.

2) Iterate over all children of ScrollFunction, as you proposed. The code
   might roughly look like this:

     Dim hControl As Control

     For Each hControl In ScrollFunction.Children
       If hControl Is CheckBox Then
         ' Here you have one of the CheckBoxes in ScrollFunction.
       Endif
     Next

   Here comes the second thing which Bruce mentioned: You can assign every
   control a Tag to identify it. You could also use the Name property and
   leave Tag for some additional data. It's up to you and your program
   design and goals what you will put into the If clause...

Regards,
Tobi




More information about the User mailing list