Search code examples
vb.net.net-2.0

Radiobutton in groupbox is not working properly


 Public Class Form1

Dim RadioButtonNo As Integer

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    If RadioButton1.Checked = True Then
        RadioButtonNo = 1
    End If
    If RadioButton2.Checked = True Then
        RadioButtonNo = 2
    End If
    If RadioButton3.Checked = True Then
        RadioButtonNo = 3
    End If
    If RadioButton4.Checked = True Then
        RadioButtonNo = 4
    End If

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    MessageBox.Show("Selected Radio Button is : " + RadioButtonNo.ToString())
End Sub
End Class

The above code i'm using. radio button1 and radio button2 i kept in groupbox 1. radiobutton 3 and radio button 4 i kept in group box2. when i'm running the program, by default radio button 3 is selected. and if i select radio button 1 then it's not giving the correct output. i want only one radio button will be selected. and if i click button 1 then it will store that radio button value. then if i press button2 then it will show which button was selected. is it possible in groupbox? please help me.


Solution

  • As others have said, they really should be in the same groupbox...but if you really need this to work you could use an event handler to uncheck the other RadioButtons.

    Something like:

    Private Sub uncheck_radios(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged, RadioButton2.CheckedChanged, RadioButton3.CheckedChanged, RadioButton4.CheckedChanged
        Dim rad As RadioButton = sender
        If rad.Checked Then
            Select Case Strings.Right(rad.Name, 1)
                Case "1", "2"
                    RadioButton3.Checked = False
                    RadioButton4.Checked = False
                Case "3", "4"
                    RadioButton1.Checked = False
                    RadioButton2.Checked = False
            End Select
        End If
    End Sub