Codie Vincent
Codie Vincent

Reputation: 187

How to get the text value out of a radio button list

So I have two group boxes, what I am wanting is to get the selected radio button value from both of them.

If it was just a text box you can go:

thisValue = textbox1.text

But I have no idea how to do it for a radio button

Upvotes: 0

Views: 6761

Answers (3)

Hess Cheng
Hess Cheng

Reputation: 1

Reference to same click event trigger

private void rb_Click(object sender, EventArgs e) {
    thisValue = ((RadioButton)sender).Text;
}

Upvotes: 0

Camilo Sanchez
Camilo Sanchez

Reputation: 1515

this is WindowsForms Linq example if it doesn't work exactly you'd get the idea

RadioButton rb = null;
RadioButton checkedRB = groupBox1.Controls.FirstOrDefault(
c => (rb = c as RadioButton) != null && rb.Checked) as RadioButton;

if (checkedRB != null)

{
this.Text = checkedRB.Text;
}

Upvotes: 0

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

To get the value (assuming that you want the value, not the text) out of a radio button, you get the Checked property:

bool isChecked = radioButton1.Checked;

There is no code-based relation between the radio buttons in a GroupBox (other than the radio buttons behaving in a manner so that only one of the radio buttons within the same container is checked at a time); your code will need to keep track of which one that is checked.

The simplest way to do this is perhaps to make the radio buttons within a group box all trigger the same event listener for the CheckedChanged event. In the event you can examine the sender argument to keep track of which one that is currently selected.

Example:

private enum SearchMode
{
    TitleOnly,
    TitleAndBody,
    SomeOtherWay
}
private SearchMode _selectedSearchMode;
private void SearchModeRadioButtons_CheckedChanged(object sender, EventArgs e)
{
    RadioButton rb = (RadioButton)sender;
    if (rb.Checked)
    {
        if (rb == _radioButtonTitleOnly)
        {
            _selectedSearchMode = SearchMode.TitleOnly;
        }
        else if (rb == _radioButtonTitleAndBody)
        {
            _selectedSearchMode = SearchMode.TitleAndBody;
        }
        else
        {
            // and so on
        }
    }            
}

Upvotes: 2

Related Questions