Object looping ?

  • Thread starter Deasun O'Donnachadha
  • Start date
D

Deasun O'Donnachadha

Good evening,

I have a panel with a number of labels and textboxes.
I want to set the text boxes to readonly = false.
This is what I have;

Dim objTxtBox As New TextBox
For Each objTxtBox In pnl_FB_Details.Controls
objTxtBox.ReadOnly = False
Next

I get err msg: cast not valid.
What am I doing wrong ?

Thanks
Deasun
 
M

Marina

You are assuming every object is a Textbox - which it isn't. So the cast
fails when you encounter something that's not an object. Additionally,
there is no need to initialize objTxtBox to a new instance of textbox -
since you never actually use it.

Something like this should work:

For Each ctl as Control In pnl_FB_Details.Controls
If typeof(ctl) Is TextBox
ctl.ReadOnly = False
End If
Next
 
K

Kevin Spencer

You're doing a couple of things wrong, one of which you're not aware of:
Dim objTxtBox As New TextBox

That won't throw an Exception, but why instantiate a new TextBox when you're
going to do nothing with it but replace it with TextBoxes in the Form?
That's a waste of processing and memory. Do this instead:
Dim objTxtBox As TextBox

Tip: Don't use coding shortcuts unless you understand them.

Second error: A Control's collection is a collection of Controls, not
TextBoxes. You have to cast each control that is a TextBox to the type
TextBox. Example:

Dim intCt As Integer
For intCt = 0 to pnl_FB_Details.Controls.Count - 1
CType(pnl_FB_Details.Controls(intCt), TextBox).ReadOnly = False
Next

- or -

Dim objControl As Control
For Each objControl in pnl_FB_Details.Controls
CType(objControl, TextBox).ReadOnly = False
Next


One more thing: Make sure that if you use the above code, there are no
Controls on that Panel that are NOT TextBoxes. Otherwise, you may have to
use Reflection to determine whether any given Control is a TextBox.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
http://www.takempis.com
Neither a follower nor a lender be.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top