我想在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必须具有较低的索引,从零开始。似乎它有效,但我不确定这是否是一个很好的解决方案。也许还有更多的方法可以做同样的事情。
答案 0 :(得分:2)
这会为您提供Checked
RadioButton
:
private void radioButtons_CheckedChanged(object sender, EventArgs e)
{
RadioButton rb = sender as RadioButton;
if (rb.Checked)
{
Console.WriteLine(rb.Text);
}
}
其Parent
的Controls集合中的任何索引都是 volatile 。
您可以像这样访问它:rb.Parent.Controls.IndexOf(rb)
如果您想要除Name
和Text
之外的相对稳定的 ID,则可以将其放在Tag
中。
显然,您需要将此事件与所有组中的RadionButtons
联系起来。
不需要(或推荐)类型检查,因为只有RadioButton
可以(或者更确切地说:必须)触发此事件。
答案 1 :(得分: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);
...
}