How to get a checked radio button in a groupbox? [duplicate]
Asked Answered
P

11

18

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?

Pacifier answered 24/6, 2011 at 11:14 Comment(1)
Does this answer your question? Which Radio button in the group is checked?Glasshouse
R
47

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

Resplendent answered 24/6, 2011 at 12:9 Comment(3)
The Where is not needed as you can pass a Lambda expression to the FirstOrDefault() method too.Clearheaded
This is a good solution. You could make it more simple by replacing the .Where with .SingleOrDefault and removing the .FirstOrDefault.Dordrecht
This just saved me from writing a HUGE if statementGreene
C
8

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!

Clearheaded answered 24/6, 2011 at 11:27 Comment(3)
i think in vb.net instead of Children you need to use ControlsResplendent
you are correct. Not just in VB in C# as well; it is a property name. I was mixing up with WPF/SilverlightClearheaded
'IsChecked' is not a member of 'RadioButton'Vernalize
B
7
'returns which radio button is selected within GroupBox passed
Private Function WhatRadioIsSelected(ByVal grp As GroupBox) As String
    Dim rbtn As RadioButton
    Dim rbtnName As String = String.Empty
    Try
        Dim ctl As Control
        For Each ctl In grp.Controls
            If TypeOf ctl Is RadioButton Then
                rbtn = DirectCast(ctl, RadioButton)
                If rbtn.Checked Then
                    rbtnName = rbtn.Name
                    Exit For
                End If
            End If
        Next
    Catch ex As Exception
        Dim stackframe As New Diagnostics.StackFrame(1)
        Throw New Exception("An error occurred in routine, '" & stackframe.GetMethod.ReflectedType.Name & "." & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'." & Environment.NewLine & "  Message was: '" & ex.Message & "'")
    End Try
    Return rbtnName
End Function
Budweis answered 9/11, 2012 at 17:24 Comment(1)
The other answers are a little cleaner, but this is interesting as a brute-force method that doesn't require the names of the controls.Cirrostratus
C
2

I know it is tagged vb.net but here is a c# example

var checkedButton = GroupBox1.Controls.OfType<RadioButton>()
                                      .FirstOrDefault(rb => rb.Checked);
Cetology answered 7/8, 2012 at 11:0 Comment(0)
C
1

Here is a test program with a groupbox with four radio buttons.

Public Class Form1

    Private Sub Form1_Shown(sender As Object, _
                            e As System.EventArgs) Handles Me.Shown
        RadioButton1.Tag = New Action(AddressOf rb1Action)
        RadioButton2.Tag = New Action(AddressOf rb2Action)
        RadioButton3.Tag = New Action(AddressOf rb3Action)
        RadioButton4.Tag = New Action(AddressOf rb4Action)
    End Sub

    Private Sub rb1Action()
        Debug.WriteLine("1 " & RadioButton1.Checked)
    End Sub

    Private Sub rb2Action()
        Debug.WriteLine("2 " & RadioButton2.Checked)
    End Sub

    Private Sub rb3Action()
        Debug.WriteLine("3 " & RadioButton3.Checked)
    End Sub

    Private Sub rb4Action()
        Debug.WriteLine("4 " & RadioButton4.Checked)
    End Sub

    Private Sub RadioButton_CheckedChanged(sender As System.Object, _
                                            e As System.EventArgs) Handles _
                                        RadioButton1.CheckedChanged, _
                                        RadioButton2.CheckedChanged, _
                                        RadioButton3.CheckedChanged, _
                                        RadioButton4.CheckedChanged

        Dim aRadioButton As RadioButton = DirectCast(sender, RadioButton)
        If aRadioButton.Checked Then
            Dim rbAct As Action = DirectCast(aRadioButton.Tag, Action)
            rbAct.Invoke()
        End If
    End Sub
End Class
Charlton answered 24/6, 2011 at 13:3 Comment(0)
G
0

You can run a foreach loop to iterate with the scans of controls RadioButton inside the GroupBox, so using the Control, see example below.

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    'RadioButton checked
    Dim ceckedRadioButton As Integer = 0
    'Total RadioButton on GroupBox
    Dim totalRadioButton As Integer = 0

    'Iteration and check RadioButton selected
    For Each myControl As RadioButton In Me.GroupBox1.Controls.OfType(Of RadioButton)()
        'If RadioButton is checked
        If myControl.Checked Then
            'increases variable ceckedRadioButton
            ceckedRadioButton += 1
        End If

        'increases variable totalRadioButton
        totalRadioButton += 1
    Next

    If ceckedRadioButton > 0 Then
        'RadioButon show how many are selected
        MessageBox.Show("Were selected" & " " & ceckedRadioButton.ToString & " " & "RadioButton on" & " " & totalRadioButton.ToString)
    Else
        'No selected RadioButton
        MessageBox.Show("No selected RadioButton")
    End If
End Sub

Bye

Gertrudgertruda answered 2/7, 2011 at 21:58 Comment(0)
G
0

I have simple one and easy

For Each b As RadioButton In GroupBox1.Controls.OfType(Of RadioButton)()
        If b.Checked = True Then
            MsgBox("I hope that will help you")
        End If
    Next
Gallop answered 31/3, 2013 at 23:3 Comment(0)
F
0

There are 3 RadioButtons: RadioButton1, RadioButton2 y RadioButton3

'A handler for the click event of the 3 buttons is created
Private Sub Radios_Click(sender As Object, e As EventArgs) Handles RadioButton1.Click, RadioButton2.Click, RadioButton3.Click
    Dim rb As RadioButton
    rb = sender
    MsgBox(rb.Name) 'Displays the name of the selected control or that he was made the click
End Sub
Foredeck answered 17/10, 2014 at 4:26 Comment(0)
E
0

I have created three radio buttons from the item names from a table. I also create an event handler for that. Now when I try to get which button is checked by its text value in a msgbox.It shows the correct name but msgbox popup twice for a single choice.I am using VB.net 2012.

Private Sub iButton_checked(ByVal sender As System.Object, ByVal e As System.EventArgs)
    For Each b As RadioButton In grpgodown.Controls.OfType(Of RadioButton)()
        If b.Checked = True Then
            MsgBox(b.Text)
        End If
    Next
End Sub
Epigene answered 26/3, 2017 at 9:22 Comment(0)
M
0
Private Sub BTN_OK_Click(sender As Object, e As EventArgs) Handles BTN_OK.Click

    For Each Ctrl In GroupBox1.Controls
        If Ctrl.checked Then MsgBox(Ctrl.text) 'for show select RadioButton Check
    Next
Matildematin answered 2/9, 2017 at 8:47 Comment(0)
A
-3
Select Case True
    RadioButton1.checked
        'Do this action for Rad1
    RadioButton2.checked
        'Do this action for Rad2
    RadioButton3.checked
        'Do this action for rad3
End Select
Antiquary answered 7/8, 2015 at 16:43 Comment(1)
This is a very brute force attempt, with minimal difference to the large if-elseif-then block the OP was trying to avoid.Armistead

© 2022 - 2024 — McMap. All rights reserved.