Reputation: 57
in VB.NET i have 2 custom controls, one is a TextBox and second one is a ComboBox. These have custom values like Bool _IsHidden and are added on runtime to a form.
Now, at some point in the code I want to check if the _IsHidden is set to True or False and display that information. Since the user can edit this values when creating the control these are not set on creation.
So what I tried is:
(all of this is on MDI Forms)
For Each frm as CustomForm in Main.MdiChildren
If frm.MyName = calledBy Then 'this part is just to know which form called the form to create the object
For Each cntrl as CustomTextBox in frm.Controls
'DO Something
Next
End if
Next
Now.. if the first control is a custom ComboBox it thorws an error since it sees that it does not match the custom TextBox control..
how do i get around this? By my understanding it should just go through all of the controls on the said form and just check those who match CustomTextBox control ?
Thank you
Upvotes: 1
Views: 603
Reputation: 172270
For Each x As T In collection
does not filter your collection items to those of type T
. It tries to convert every item in collection
to T
and throws an exception if that fails.
Thus, you have the following options:
Do the check yourself, for example, using the code provided by RB.
Alternatively, you could filter your list first, and then loop through the items. Here, LINQ can help:
For Each cntrl In frm.Controls.OfType(Of CustomTextBox)()
... ' Do this for all CustomTextBoxes
Next
For Each cntrl In frm.Controls.OfType(Of CustomComboBox)()
... ' Do this for all CustomComboBoxes
Next
You don't need the As CustomTextBox
clause here, since frm.Controls.OfType(Of CustomTextBox)()
returns an IEnumerable(Of CustomTextBox)
, so For Each
can infer by itself that cntrl
must be of type CustomTextBox
.
Upvotes: 4
Reputation: 37192
By my understanding it should just go through all of the controls on the said form and just check those who match CustomTextBox control ?
That's not correct I'm afraid. You'll need to implement that check yourself, e.g:
For Each cntrl as object in frm.Controls
If TypeOf cntrl Is CustomTextBox Then
With CType(cntrl, CustomTextBox)
.DoSomethingWithControl()
.DoSomethingElseWithControl()
End With
End If
Next
Upvotes: 0