C# 如何获取单选按钮所选项目的文本?
这是我的单选按钮C# 如何获取单选按钮所选项目的文本?,c#,radio-button,C#,Radio Button,这是我的单选按钮 Runescape Maplestory League 这是我目前的方法,它运行得非常好 private void button1_Click(object sender, EventArgs e) { if (radioButton1.Checked) { MessageBox.Show("You are playing Runescape."); } else if (radioButton2.Checked) {
Runescape
Maplestory
League
这是我目前的方法,它运行得非常好
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
MessageBox.Show("You are playing Runescape.");
}
else if (radioButton2.Checked)
{
MessageBox.Show("You are playing Maplestory.");
}
else if (radioButton3.Checked)
{
MessageBox.Show("You are playing League.");
}
}
我想知道是否有一种方法可以像组合框一样打印SelectedItem。基本上,单选按钮的文本
组合框版本:
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("You are playing " + comboBox1.SelectedItem);
}
类似这样的事情不确定是否可能
MessageBox.Show("You are playing " + RadioButton.SelectedItem);
您可以使用RadioButton的文本属性
解决方案2:RadioButton控件没有SelectedItem属性
但您可以创建一个函数,返回所选单选按钮的名称
试试这个:
private String getSelectedRadioButtonName()
{
foreach (Control c in groupBox1.Controls)
{
if (c is RadioButton && ((RadioButton) c).Checked==true)
{
return c.Text;
}
}
return "No Game";
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("You are playing "+getSelectedRadioButtonName());
}
您可以使用RadioButton的文本属性
解决方案2:RadioButton控件没有SelectedItem属性
但您可以创建一个函数,返回所选单选按钮的名称
试试这个:
private String getSelectedRadioButtonName()
{
foreach (Control c in groupBox1.Controls)
{
if (c is RadioButton && ((RadioButton) c).Checked==true)
{
return c.Text;
}
}
return "No Game";
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("You are playing "+getSelectedRadioButtonName());
}
我可以让它不使用if语句吗?类似于更新的组合框code@puretppc:RadioButton中没有SelectedItem属性,但您可以创建一个满足您需要的函数。请参阅我编辑的答案和部分解决方案2。@puretppc:请参阅解决方案2中完整编辑的答案。如果您不介意,请将其标记为答案:@puretppc:然后您需要更改它。控件对于foreach循环中的groupBox1.Controls,请参阅我编辑的答案它工作得非常好:@puretppc:欢迎您:很高兴能为您提供帮助。我可以将其设置为不使用if语句吗?类似于更新的组合框code@puretppc:RadioButton中没有SelectedItem属性,但您可以创建一个满足您需要的函数。请参阅我编辑的答案和部分解决方案2。@puretppc:请参阅解决方案2中完整编辑的答案。如果您不介意,请将其标记为答案:@puretppc:然后您需要更改它。控件对于foreach循环中的groupBox1.Controls,请参阅我编辑的答案,它工作得非常好:@puretppc:欢迎您:很高兴能为您提供帮助。