Search code examples
sqldatabasevb.netformsradio-button

How to Get which Radio Button is Checked in a Groupbox then insert it to a database vb.net


I want to insert a record in a database with two Groupbox. rdGender (has Male and female radio buttons) and rd ( has Owner and Driver radio buttons) in vb.net

enter image description here


Solution

  • The simplest option is to use a bit of LINQ, e.g.

    Dim checkedRadioButton = myGroupBox.Controls.
                                        OfType(Of RadioButton)().
                                        FirstOrDefault(Function(rb) rb.Checked)
    

    That will give you the RadioButton that is checked or Nothing if none is checked. That means that you'll have to test for Nothing before using the value of the variable. If you know for a fact that one will be checked, e.g. one is checked by default or you don't enable a Button to save until one is, then you can use First instead of FirstOrDefault and omit the null check.