Jan 20, 2011

Get Selected Radio button’s Text in C# windows app

The object is to get selected radio button's text in windows app using C#. It can be done in many ways. Suppose you have one group box having radio-buttons. You have to show selected radio button’s text on OK button click.

radio button c# windows appMethod 1(Traditional Approach):

1. Write following code:


String selectedText;

private void radioButton_CheckedChanged(object sender, EventArgs e)
        {
           if (((RadioButton)sender).Checked)
            selectedText = ((RadioButton)sender).Text;  
        }
private void buttonOK_Click(object sender, EventArgs e)
        {
            MessageBox.Show(selectedText,"Selected Item");  
        }

2. Now, for each radio button, Goto properties > events > give radioButton_CheckedChanged method name in CheckedChanged event and save it.

3. When you run app, select any option, radioButton_CheckedChanged is fired and text is stored in the variable and it is displayed in messagebox on button click.

I don’t like 2 step. Suppose you have many radio buttons then it is time consuming to set event for all. So, I prefer second method.


Method II:

In this method, I created a method GetSelectedRadioButtonText which accepts groupbox as a parameter and returns selected radio button’s text.


private string GetSelectedRadioButtonText(GroupBox grb) {
           return grb.Controls.OfType<RadioButton>().SingleOrDefault(rad => rad.Checked == true).Text;   
        }
private void buttonOK_Click(object sender, EventArgs e)
        {
            MessageBox.Show(GetSelectedRadioButtonText(groupBox1), "Selected Item");  
        }

Hope, It helps.