-1


I've a C# Windows Form Application that contains multiple Groups , each group contains some of Radio Buttons. I want to insert values of each group to my ACCESS database table. I’am trying to return from every function like doing

private void Get_Gender(RadioButton GenderButton)
        {
            if (GenderButton.Checked)
            {
                Return GenderButton.Text;
            }
        }

private void Get_Age(RadioButton AgeButton)
        {
            if (AgeButton.Checked)
            {
                Return AgeButton.Text;
            }
        }
private void Get_Interest(RadioButton InterestButton)
        {
            if (InterestButton.Checked)
            {
                Return InterestButton.Text;
            }
        }

Then trying to pick them from functions like

String Gender = Get_Gender(I don’t know what to put here);
String Age= Get_Age(I don’t know what to put here);
String Interestr = Get_Interest(I don’t know what to put here);

And then create connection..(this will be no problem)

OleDbConnection con = new OleDbConnection();
Command cmd = new oleDbCommand(“INSERT into tbl (Age, Gender, Interest) “+”values(@age, @gend, @int”, con);  

Query will not be problem ,

 but values of those three groups.
Getting those values (@age, @gend, @int”, con); 

getting me crazy… Is There a simple way to get just the checked RadioButton by code instead of checking every Radio Button in each group whether it is checked or not ? Pls se my image.. to understand more. Pls help guys and thank you in advance.

Jonas Willander
  • 432
  • 3
  • 9
  • 29

1 Answers1

0

You could pass in a list of radio button objects, loop through them until you get the first selected. The main issue is they are different objects, even though they are grouped and can only have one selected.

var radioButtons = new List<RadioButton>();
radioButton.Add(Form.rbGenderMale);
radioButton.Add(Form.rbGenderFemale);

then your Get_Gender method can be like

private void Get_Gender(List<RadioButton> genderButtons)
{
    foreach (var genderButton in genderButtons)
    {
        if (genderButton.Checked)
        {
            return genderButton.Text;
        }
     }
 }

If you are using dynamic radio buttons or don't care of the effects reflection will have but like the idea of adding new radio buttons to your form group without having to change code behind then take a look at How to get a checked radio button in a groupbox?

Community
  • 1
  • 1
Jacob Roberts
  • 1,725
  • 3
  • 16
  • 24
  • Thank you Shifty. Is this code for c# (cSharp) ? I can't use the first row: var radioButtons = new List(); the keyword " var " giving me error. – Jonas Willander Apr 10 '15 at 07:21
  • Yes, it's c#. You can always be more explicit and do `List radioButton = new List();` var is just a shortcut for the compiler to it. – Jacob Roberts Apr 10 '15 at 13:27