Accessing form controls

pachjo

Well-known member
Joined
Dec 12, 2006
Messages
370
Programming Experience
10+
Can someone tell me why the following works:

VB.NET:
Me.rad12Months.Checked = True

But this does not:

VB.NET:
Me.Controls.Item("rad12Months").Checked = True

or even:

VB.NET:
Messagebox.Show(Me.Controls.Item("rad12Months").GetType.ToString)

The last two error with object not set

Thnx
 
VB.NET:
        Dim c As CheckBox = CType(Me.Controls("rad12Months"), CheckBox)
        MessageBox.Show(c.Checked.ToString)

or even

VB.NET:
        Dim strWhichCheckBox As String = "rad12Months"
        Dim c As CheckBox = CType(Me.Controls(strWhichCheckBox), CheckBox)
        MessageBox.Show(c.Checked.ToString)
 
Last edited:
But this does not:

VB.NET:
Me.Controls.Item("rad12Months").Checked = True

or even:

VB.NET:
Messagebox.Show(Me.Controls.Item("rad12Months").GetType.ToString)

The last two error with object not set

Thnx
The first errors because Control class doesn't have Checked property. You can CType/DirectCast the control to correct type as mentioned. If the second doesn't work it is because rad12Months isn't part of Me.Controls collection, most likely it belongs to a different container control. For example Me.Panel1.Controls("rad12Months")
 
Thanks Chaps!

Yep, it is buried in a panel within a panel within a group control and hey presto it works ;)

However how come this works

me.mycheckbox.checked=True

but when using a somthing like this does not, how come the above finds it so easy?

Me.Controls.Item("rad12Months").checked=True

I get what you mean about checked not being a member but how does the first line access the control without the need to drill down into the panels?
 
"mycheckbox" is a class field (a variable), look at the Designer generated code and you see it declared "Friend WithEvents mycheckbox As CheckBox" and in InitializeComponent method "mycheckbox = New CheckBox" and later something like "Groupbox1.Controls.Add(mypanel)"....
 
Back
Top