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.
Method 1(Traditional Approach):
1. Write following code:
01
02
03
04
05
06
07
08
09
10
11
|
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_CheckedChangedmethod 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.
1
2
3
4
5
6
7
|
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.
转自:http://techbrij.com/get-selected-radio-button-text-windows-app-net