How to Looping through all NumericUpDown and check the value?
For Each control As Control In Me.Controls
Dim numControls As NumericUpDown = TryCast(control, NumericUpDown)
If numControls.Value > 14 Then
MsgBox("ok")
End If
Next
the one i tried but didnt work
CodePudding user response:
If it's not acceptable to have less than 15 in any of your NumericUpDowns, then set their Minimum property to 15, obviating this check entirely
If for some reason you still need to do it I'd recommend something like
If Me.Controls.OfType(Of NumericUpDown).Any(Function(nud) nud.Value < 15)) Then ...
This way you do something once if any of them are less than 15.
Try and avoid using MessageBoxes if you can; they're very disruptive to user flow through a UI. Certainly having 10 NUD on a form and if they're all over 14 showing 10 "ok" messageboxes in a row will be incredibly annoying for the user
CodePudding user response:
What you have done makes some sense but it has a glaring flaw. The whole point of TryCast
is that it returns Nothing
if the cast fails rather than throwing an exception. You then go ahead and use that result as though it's not Nothing
and cause a NullReferencxeException
anyway. If you are using TryCast
then you ALWAYS need to be testing the result for Nothing
. If you don't need to do that because you know the result will not be Nothing
then you shouldn't be using TryCast
in the first place.
Dim numControls = TryCast(control, NumericUpDown)
If numControls IsNot Nothing AndAlso numControls.Value > 14 Then
That said, you can cast and filter in one go, so there's no need for that:
For Each numControls In Me.Controls.OfType(Of NumericUpDown)
If numControls.Value > 14 Then
The example code also assumes that the controls have been added to the form directly. If they have been added to some other container, e.g. a Panel
, then you need to use the Controls
collection of that container rather than the form.