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

一曲冷凌霜 提交于 2019-12-24 22:12:41

问题


Here are my radio buttons

Runescape
Maplestory
League

So this is my current method and it runs perfectly fine.

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.");
    }
}

I want to know if there is a way I can print out the SelectedItem kinda like a combo box. Basically, the text of the radio button.

Combobox version:

private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show("You are playing " + comboBox1.SelectedItem);
}

Something along the lines of this (not sure if it is possible).

MessageBox.Show("You are playing " + RadioButton.SelectedItem);

回答1:


you can use Text property of RadioButton .

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

Solution 2: there is no SelectedItem Property for RadioButton control.

but you can create a function which will return the Name of the selected RadioButton

Try this:

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


来源:https://stackoverflow.com/questions/20308619/how-do-i-get-the-text-of-the-radio-button-selected-item

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!