user3098326
user3098326

Reputation: 229

Changing properties of all textbox in the same form VB.NET

I'm looking for a way to solve this code :

     For Each txtbox As TextBox In Me.Controls
        If txtbox.GetType.ToString = "System.Windows.Form.TextBox" Then
            CType(txtbox, TextBox).CharacterCasing = CharacterCasing.Upper
        End If
     Next

it throws error :

Unable to cast object of type 'System.Windows.Forms.Button' to type 'System.Windows.Forms.TextBox'.

Upvotes: 0

Views: 2538

Answers (2)

OneFineDay
OneFineDay

Reputation: 9024

Make an array of textbox objects, without worrying about casting. Better performance since we are not checking types.

For Each tb As Textbox In Me.Controls.OfType(Of Textbox)()
 tb.CharacterCasing = CharacterCasing.Upper
Next

Upvotes: 2

rory.ap
rory.ap

Reputation: 35290

The problem is you're looping through all the controls, even the buttons, and trying to cast each to a textbox which will throw the exception you got when it does so for a button (or other non-textbox control).

Try this:

 For Each ctrl As System.Windows.Forms.Control In Me.Controls
    If TypeOf ctrl Is System.Windows.Forms.TextBox Then
        CType(ctrl, System.Windows.Forms.TextBox).CharacterCasing = CharacterCasing.Upper
    End If
 Next

Upvotes: 1

Related Questions