Click here to Skip to main content
15,894,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 7 radio buttons in a group box. I have the following code
private void initgrpBox1()
{
  groupBox1.Controls.Add(radioButton1);
  groupBox1.Controls.Add(radioButton2);
  groupBox1.Controls.Add(radioButton3);
  groupBox1.Controls.Add(radioButton4);
  groupBox1.Controls.Add(radioButton5);
  groupBox1.Controls.Add(radioButton6);
  groupBox1.Controls.Add(radioButton7);
  Controls.Add(groupBox1);
}

I want to set a alphabet for each radio button checked in the group box.
I tried using foreach statement to traverse through the radiobuttons in groupbox,but it's not working
//foreach(rad as RadioButton in groupBox1.controls )

Please let me know how to check whether a radio button in checked.
Posted
Updated 14-Oct-19 11:19am
v3

Let's assume this is System.Windows.Forms.

Create some data type you need for identification of the action related to the radio button. Let's assume this is a enumeration expressing some option set, but it can be anything:

C#
enum RadioOption {
   None, Good, Bad, Fair, Excellent, Perfect,
}


Now, add this data as a Control.Tag (which is of the type System.Object:

C#
RadioButton rb = new Radio(button);
rb.Tag = RadioOption.Good;
rb.Name = string.Format("&{0}", RadioOption.Good); 
rb.Top = //...
//...
groupBox1.Controls.Add(rb);
rb = new Radio(button);
rb.Tag = RadioOption.Perfect;
rb.Name = string.Format("&{0}", RadioOption.Perfect); 
rb.Top = //...
//...
groupBox1.Controls.Add(rb);


Now, you need to extract this information from a selected radio button:

C#
static RadioOption GetOption(RadioButton radio) {
    return (RadioOption)radio.Tag;
}


You should make sure that the method above is only called for the radio buttons "tagged" using the method shown above. You can put any other information in the tag. Define the type you need, depending on how you want to use it.

A very good use of it is the event RadioButton.CheckedChanged.
For each of them do the following:

C#
rb.CheckedChanged += (sender, eventArgs) => {
   RadioButton aButton = (RadioButton)sender;
   RadioOption option = GetOption(sender as RadioButton);
   DoSomethingWhenCheckedChanged(aButton.Cheched, option);
}; //rb.CheckedChanged


—SA
 
Share this answer
 
v5
Comments
Olivier Levrey 30-Mar-11 4:39am    
Perfect answer with good advices. My 5. (just fixed a code tag).
Sergey Alexandrovich Kryukov 30-Mar-11 4:41am    
Thank you, Olivier.
--SA
johannesnestler 30-Mar-11 4:56am    
very good advices - your solutions always show your practical experience.
Sergey Alexandrovich Kryukov 30-Mar-11 16:18pm    
Thank you. Well... sometimes they do.
--SA
Just handle the Clicked event for all of the radio buttons in the group in a single event handler, and store the clicked radio button as a separate var, something like this:

C#
public partial class MyForm
{
    RadioButton m_radiogroup1Checked = null;

    private void initgrpBox1()
    {
        AddRadioToGroupBox(groupBox1, radioButton1);
        AddRadioToGroupBox(groupBox1, radioButton2);
        AddRadioToGroupBox(groupBox1, radioButton3);
        AddRadioToGroupBox(groupBox1, radioButton4);
        AddRadioToGroupBox(groupBox1, radioButton5);
        AddRadioToGroupBox(groupBox1, radioButton6);
        AddRadioToGroupBox(groupBox1, radioButton7);
        Controls.Add(groupBox1);
    }

    private void AddRadioToGroupBox(GroupBox groupBox, RadioButton radioButton)
    {
        groupBox.Controls.Add(radioButton);
        radioButton.Clicked += new EventHandler(radioGroup1Checked);
    }

    private void radioGroup1_Clicked(object sender, e EventArgs)
    {
        m_radiogroup1Checked = sender as RadioButton;
    }
}


This way, there's not nearly as much extra code write (as shown in the other solutions). Just let the form do its thing, and any time you want, you can check the value of m_radiogroup1Checked to see which button was checked.

Easy peesy, lemon squeezy...

You could also create a RadioGroup class that handled all this stuff for you...
 
Share this answer
 
v3
Comments
johannesnestler 30-Mar-11 8:21am    
yep, a good aproach for the OP!
You could try this

foreach (RadioButton rb in groupBox1.Controls)
           {
               MessageBox.Show(rb.Name);
           }


But this would break if there are ohter controls than RadioButton in your GroupBox

So you better use this:

foreach (Control c in groupBox1.Controls)
            {
                if (c.GetType() == typeof(RadioButton))
                {
                    RadioButton rb = c as RadioButton;
                    if (rb.Checked)
                    {
                        MessageBox.Show(rb.Name); 
                    }
                }
            }
            }
 
Share this answer
 
Comments
dadrock52 24-Feb-13 19:58pm    
(Y)
very good
-------
I hope To be moslem
to Worship Only One God ALLAH
Add a new check changed event for each of these buttons.

For e.g.
radiobutton1.CheckedChanged +=new EventHandler(radiobutton1_CheckedChanged);

You should then be able to monitor the checkchanged event.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 30-Mar-11 3:28am    
Abhinav, the problem is: you did not answer the question "how to know which one?". The event was not asked about.
However, I put more complete answer, please see.
I just want to point out an alternate. Maybe this is not the best solution for you, but who knows?
Others showed that looping over the GroupBox-Controls needs some testing for correct type and maybe also for the RadioButtons you are interested in. My solution only adds a dedicated array for storing the references to the RadioButtons - easy to loop over them. As option I show how to get the Checked RadioButton with Linq.

using System;
using System.Linq;
using System.Windows.Forms;

namespace AreYouChecked
{
    static class Program
    {
        static void Main()
        {
            const int iNR_RADIO_BUTTONS = 7;
            // Create a Form
            Form form = new Form();
            // ... and a GroupBox
            GroupBox groupbox = new GroupBox();
            groupbox.Dock = DockStyle.Fill;
            // Store the RadioButtons in an dedicated array
            RadioButton[] aRadioButtons = new RadioButton[iNR_RADIO_BUTTONS];
            // ... and add them to the GroupBox
            for (int i = aRadioButtons.Length - 1; i >= 0; i--)
            {
                aRadioButtons[i] = new RadioButton();
                aRadioButtons[i].Dock = DockStyle.Top;
                aRadioButtons[i].Text = "Option" + i;
                groupbox.Controls.Add(aRadioButtons[i]);
            }
            // Create a Button for testing
            Button buttonAsk = new Button();
            buttonAsk.Dock = DockStyle.Bottom;
            buttonAsk.Text = "Which RadioButton checked?";
            buttonAsk.Click += delegate(object sender, EventArgs e)
            {
                // Find out which RadioButton is checked:
                // 
                // Option1: loop over the dedicated array
                RadioButton rbIamChecked = null;
                foreach (RadioButton rb in aRadioButtons)
                {
                    if (rb.Checked)
                    {
                        rbIamChecked = rb;
                        break; // don't forget to break here, only one RadioButton should be checked!
                    }
                }
                // Option2: use Linq
                //try
                //{
                //    rbIamChecked = aRadioButtons.Single(r => r.Checked);
                //}
                //catch (InvalidOperationException ex)
                //{
                //    // none/multiple checked 
                //}
                //
                // Do something 
                MessageBox.Show(rbIamChecked != null ? rbIamChecked.Text : "None");
            };

            // Add Controls to the Form
            form.Controls.Add(groupbox);
            form.Controls.Add(buttonAsk);
            // ... and Show it;
            Application.Run(form);
        }
    }
}
 
Share this answer
 
v2
var buttonsChecked = groupBox1.Controls.OfType<RadioButton>()
               .FirstOrDefault(a => a.Checked);
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900