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.
Dim btn = myFlowLayoutPanel.Controls.
OfType(Of Button)().
FirstOrDefault(Function(b) b.Text = myText)
Note that that code will work whether all the child controls are Buttons
or not, as OfType
ensures that anything but a Button
is ignored. If you know that every child control is a Button
though, it would be more efficient to do this:
Dim btn = myFlowLayoutPanel.Controls.
Cast(Of Button)().
FirstOrDefault(Function(b) b.Text = myText)
and more efficient still to do this:
Dim btn = DirectCast(myFlowLayoutPanel.Controls.
FirstOrDefault(Function(b) b.Text = myText),
Button)
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 be Nothing
and you should ALWAYS test that result for Nothing
before using it.