How to get the text value out of a radio button list
So I have tw开发者_JS百科o 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
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
}
}
}
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;
}
Reference to same click event trigger
private void rb_Click(object sender, EventArgs e) {
thisValue = ((RadioButton)sender).Text;
}
精彩评论