|
-
May 30th, 2007, 11:27 AM
#1
Thread Starter
Addicted Member
[RESOLVED] Accessing label property in controls collection
Was dynamically adding a row of buttons each with label beneath in VB6 using control arrays. No arrays in VB.net, so it seemed a neat approach just to add direct to the controls collection, eg.
For cnt = 1 To NumButt
.Controls.Add(New Button) : cptr = cptr + 1
With .Controls(cptr)
.Width = bwidth
.Height = bheight
.left = etc etc
End With
Next cnt
etc etc, similar code to add NumButt labels
This seems pretty neat and works well, I can also set text and background images. Unfortunately, in just one case I need to set TextAlign of a label and it seems that one can only access those properties that are common to all controls in the controls collection, I can't see how to access those specific to a label, even though I can see in quickwatch that it is a label.
Is there a way of doing it or do I have to rethink the entire approach?
Alternatively, any way of ensuring all labels get created with TextAlign of MiddleCenter by default or better still copy all properties from an existing control?
Cheers for any answers.
Last edited by xoggoth; May 30th, 2007 at 11:37 AM.
-
May 30th, 2007, 11:36 AM
#2
Re: Accessing label property in controls collection
First off, control arrays exist in .NET
They aren't called control arrays though, they are just arrays like any other array. The only difference between VB6 and .NET is that the controls in the array can't have the same name, and you create them dynamically...
that being said, you can only access properties of the Control class since that is what you are casting everything to by using the controls collection..
you could just cast the control to the correct type and access its specific properties that way...
Code:
if typeof .Controls(cptr) is Label then
DirectCast(.Controls(cptr),Label).TextAlign = ContentAlignment.MiddleRight
elseif typeof .controls(cptr) is Button then
'DO SPECIFIC BUTTON STUFF HERE
end if
-
May 30th, 2007, 08:42 PM
#3
Re: Accessing label property in controls collection
There's no point adding the new control to the Controls collection, then getting it back and setting its properties. Create the control, set its properties first, then add it to the collection, e.g.:
vb.net Code:
Dim btn As Button
For i As Integer = 1 To buttonCount Step 1
btn = New Button
'Set properties of btn here.
Me.Controls.Add(btn)
Next i
That way you are already accessing the object via a variable of the correct type so there's no casting required.
Also, I can see from your code that you are using nested With blocks. While it's legal that is very bad practice.
-
Jun 4th, 2007, 03:38 AM
#4
Thread Starter
Addicted Member
Re: Accessing label property in controls collection
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|