How do I get which radio button is checked from a groupbox?

…衆ロ難τιáo~ 提交于 2019-11-27 02:41:52

问题


I have these groupboxes:

I want to run some code according to checked true state of a radio button like:

string chk = radiobutton.nme; // Name of radio button whose checked is true
switch(chk)
{
    case "Option1":
        // Some code
        break;

    case "Option2":
        // Some code
        break;

    case "Option3":
        // Some code
        break;
}

Is there any direct way so that I can only get the name of the checked radio button?


回答1:


You can find all checked RadioButtons like

var buttons = this.Controls.OfType<RadioButton>()
                           .FirstOrDefault(n => n.Checked);

Also take a look at CheckedChanged event.

Occurs when the value of the Checked property changes.




回答2:


You should take some look at the CheckedChanged event to register the corresponding event handler and store the Checked radio button state in some variable. However, I would like to use LINQ here just because you have just some RadioButtons which makes the cost of looping acceptable:

var checkedRadio = new []{groupBox1, groupBox2}
                   .SelectMany(g=>g.Controls.OfType<RadioButton>()
                                            .Where(r=>r.Checked))
// Print name
foreach(var c in checkedRadio)
   System.Diagnostics.Debug.Print(c.Name);



回答3:


Rather than checking all RadioButtons, use the Validated event of the GroupBox.

private void grpBox_Validated(object sender, EventArgs e)
    {
        GroupBox g = sender as GroupBox;
        var a = from RadioButton r in g.Controls where r.Checked == true select r.Name;
        strchecked = a.First();
     }



回答4:


In my opinion, it's better if you use RadioGroup instead of GroupBox. If you use radioGroup, you can always find the selected item easily like this:

radioGroup.selectedIndex;

If you design using Windows Forms, I suggest to implement RadioGroup behavior like this (please note that my code is in Java):

for (Component comp:groupBox1.components) {
    if (((RadioButton)comp).selected)
        return ((RadioButton)comp).value;
}

You can put this code block in a method to return selected radioButton value, and then you can use this value in your SWITCH part.



来源:https://stackoverflow.com/questions/18547326/how-do-i-get-which-radio-button-is-checked-from-a-groupbox

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