I have many buttons with different text in a FlowLayoutPanel
, and I want to find the button with particular string.
I'm currently doing it this way:
Dim str as String = 'some text
For each btn as Button in FlowLayoutPanel.Controls
If btn.Text = str then
'do something with btn
End If
Next
Is it possible to do something like this?
Dim str as String = 'some text
Dim btn as Button = FlowLayoutPanel.Controls.Button.Text with that string
'do something with btn
You can use LINQ, e.g.
Note that that code will work whether all the child controls are
Buttons
or not, asOfType
ensures that anything but aButton
is ignored. If you know that every child control is aButton
though, it would be more efficient to do this:and more efficient still to do this:
The difference would be negligible though and, if efficiency is your main concern, then you probably shouldn't be using LINQ at all.
Also note that
FirstOrDefault
is only appropriate if there may be zero, one or more matches. Other methods are more appropriate in other cases:First
: There will always be at least one match but may be more then one.FirstOrDefault
: There may not be any matches and there may be more than one.Single
: There will always be exactly one match.SingleOrDefault
: There may be no matches but will never be more than one.If you use one of the
OrDefault
methods then the result may beNothing
and you should ALWAYS test that result forNothing
before using it.