繁体   English   中英

获取 radioGroup 中选定 RadioButton 的索引

[英]Get index of a selected RadioButton in radioGroup

我想在 RadioGroup 中找到所选 RadioButton 的索引。 我将下一个方法附加到组中的每个 RadioButton:

private void radio_button_CheckedChanged(object sender, EventArgs e){
    if (sender.GetType() != typeof(RadioButton)) return;
    if (((RadioButton)sender).Checked){
        int ndx = my_radio_group.Controls.IndexOf((Control)sender);
        // change something based on the ndx
    }
}

对我来说,较低的 radioButton 必须具有较低的索引,从零开始,这一点很重要。 似乎它正在工作,但我不确定这是否是一个好的解决方案。 也许有更多的 betufilul 方式来做同样的事情。

这将为您提供Checked RadioButton

private void radioButtons_CheckedChanged(object sender, EventArgs e)
{
    RadioButton rb = sender as RadioButton;
    if (rb.Checked)
    {
        Console.WriteLine(rb.Text);
    }
}

Parent的Controls集合中的任何索引都是高度不稳定的

你可以这样访问它: rb.Parent.Controls.IndexOf(rb)如果你想要一个相对稳定的 ID除了NameText你可以把它放在Tag

显然,您需要将此事件连接到组中的所有 RadionButtons

没有类型检查是真正必要的(或推荐),因为只有RadioButton可以(或者更确切地说: 必须 )触发此事件。

要理想地获取索引,您希望将控件排列为集合。 如果您可以从代码后面添加控件,那么就像那样容易

List<RadionButton> _buttons = new List<RadioButton>();

_buttons.Add(new RadioButton() { ... });    
_buttons.Add(new RadioButton() { ... });    
...

如果您想使用表单设计,那么可能在表单构造函数中创建此列表是另一种选择:

List<RadioButtons> _list = new List<RadioButton>();

public Form1()
{
    InitializeComponent();
    _list.Add(radioButton1);
    _list.Add(radioButton2);
    ...
}

然后获取索引的实际任务就像:

void radioButton_CheckedChanged(object sender, EventArgs e)
{
    var index = _list.IndexOf(sender);
    ...
}
//----checked change----

private void radioButtons_CheckedChanged(object sender, EventArgs e)
{
  int ndx = 0;
            var buttons = RdoGroup.Controls.OfType<RadioButton>()
  .FirstOrDefault(n => n.Checked);

//-----in initialize set radioButton tags : this.radioButton1.Tag = "1";------

        if (buttons.Tag != null) ndx=Convert.ToInt32( buttons.Tag.ToString());
//--------do some thing by index----------

}

暂无
暂无

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

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