2016-04-21 88 views
1

我想查找RadioGroup中选定RadioButton的索引。我连着下单方法给每个单选按钮组中:获取radioGroup中选定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 
    } 
} 

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

+0

像这样的事情http://stackoverflow.com/questions/17082551/getting-the-index-of-the-selected-radiobutton-in-a-group –

+0

你在做什么? argetting:Winforms,WPF,ASP ..? __Always__正确标记您的问题。 – TaW

+0

我一直倾向于使用单选按钮'value'属性而不是组中的索引。这允许您更改顺序,插入新项目,并且不需要在事实之后更改代码(除了处理新选项的逻辑外)。 –

回答

2

这会给你的CheckedRadioButton:在其Parent的Controls集合

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

的任何索引高度挥发性。如果你想除了Name一个相对稳定 ID rb.Parent.Controls.IndexOf(rb)Text,你可以把它放在Tag

你可以这样访问它。

显然您需要将该事件挂接到组中的全部RadionButtons

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

+0

谢谢,它适用于我。使用标签来存储期望值 –

1

要理想地获得索引,您希望将控件排列为集合。如果你可以从代码添加控件后面比那是那么容易,因为

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

您是否看到Barry链接的第一行? ; - ) – TaW

+0

@ Barry的评论? WPF一个? – Sinatr

+0

谢谢,这是有帮助的,也许我会稍后使用它 –

相关问题