繁体   English   中英

如何获得单选按钮所选项目的文本?

[英]How do I get the text of the radio button selected item?

这是我的单选按钮

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 Text属性。

private void button1_Click(object sender, EventArgs e)
    {
        if (radioButton1.Checked)
        {
            MessageBox.Show("You are playing "+radioButton1.Text);
        }

        else if (radioButton2.Checked)
        {
            MessageBox.Show("You are playing Maplestory "+"+radioButton2.Text);
        }

        else if (radioButton3.Checked)
        {
            MessageBox.Show("You are playing League "+"+radioButton3.Text);
        }
    }

解决方案2: RadioButton控件没有SelectedItem属性。

但是您可以创建一个function ,该function将返回所选RadioButtonName

尝试这个:

    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());
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM