2016-04-21 207 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

謝謝,這是有幫助的,也許我會稍後使用它 –