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
For Each x As T In collectiondoes not filter your collection items to those of typeT. It tries to convert every item incollectiontoTand 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:
You don’t need the
As CustomTextBoxclause here, sincefrm.Controls.OfType(Of CustomTextBox)()returns anIEnumerable(Of CustomTextBox), soFor Eachcan infer by itself thatcntrlmust be of typeCustomTextBox.