How to get a checked radio button in a groupbox? [duplicate]
I have a lot of radio buttons in a groupbox. Normally I will check each radio button individually using If radiobutton1.Checked = True Then
.
But I think maybe there is smart way to check which radio button being checked in a groupbox. Any idea?
Solution 1:
try this
Dim rButton As RadioButton =
GroupBox1.Controls
.OfType(Of RadioButton)
.FirstOrDefault(Function(r) r.Checked = True)
this will return the Checked RadioButton
in a GroupBox
Note that this is a LINQ query, and you must have
Imports System.Linq
If you do not, your IDE/Compiler may indicate that OfType
is not a member of System.Windows.Forms.Control.ControlCollection
Solution 2:
If you add them (Load event for instance) to a List you could use LINQ:
Dim checkedRadioButton as RadioButton
checkedRadioButton =
radioButtonList.FirstOrDefault(Function(radioButton) radioButton.Checked))
This should be OK because there is a single one checked at the most.
EDIT Even better: just query the Controls collection of the GroupBox:
Dim checkedRadioButton as RadioButton
checkedRadioButton =
groupBox.Controls.OfType(Of RadioButton)().FirstOrDefault(Function(radioButton) radioButton.Checked))
Be aware that this will cause problems if there are no RadioButtons in the Groupbox!