[英]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除了Name
和Text
你可以把它放在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.