This code permits a developer to determine if a radio button is selected in a container such as a panel or GroupBox using syntax similar to TryParse.
Requires Requires Framework 3.5 or higher
Example
Private Sub Button1_Click() Handles Button1.Click
Dim SelectedButton As New RadioButton
If GroupBox1.GetSelectedRadioButton(SelectedButton) Then
MsgBox(SelectedButton.Name)
Else
MsgBox("Please make a selection")
End If
End Sub
Extension to be placed in a code module
<System.Diagnostics.DebuggerStepThrough()> _
<System.Runtime.CompilerServices.Extension()> _
Public Function GetSelectedRadioButton(ByVal container As Control, _
ByRef Button As RadioButton) As Boolean
Dim Result As Boolean = False
Dim RadioCollection = From Control In container.Controls _
Where TypeOf Control Is RadioButton Select Control
If Not RadioCollection Is Nothing Then
Dim CheckedButton = (From Item In RadioCollection.Cast(Of RadioButton)() _
Where Item.Checked).DefaultIfEmpty(Button).First
If Not CheckedButton.Name.Equals(Button.Name) Then
Button = CheckedButton
Result = True
End If
End If
Return Result
End Function