使用WinForms;是否有更好的方法来查找组的选中RadioButton?在我看来,下面的代码应该是不必要的。当您选中一个不同的RadioButton时,它就会知道取消选中哪个…因此,它应该知道选中了哪一个。如何在不执行大量if语句(或switch)的情况下提取这些信息。
RadioButton rb = null;
if (m_RadioButton1.Checked == true)
{
rb = m_RadioButton1;
}
else if (m_RadioButton2.Checked == true)
{
rb = m_RadioButton2;
}
else if (m_RadioButton3.Checked == true)
{
rb = m_RadioButton3;
}
发布于 2009-11-26 00:02:46
您可以使用LINQ:
var checkedButton = container.Controls.OfType<RadioButton>()
.FirstOrDefault(r => r.Checked);
请注意,这要求所有单选按钮都直接位于同一容器中(例如,Panel或Form),并且容器中只有一个组。如果不是这样,您可以在构造函数中为每个组创建List<RadioButton>
,然后编写list.FirstOrDefault(r => r.Checked)
。
发布于 2009-11-26 00:01:28
您可以针对一个处理程序连接所有按钮的CheckedEvents。在那里,您可以很容易地获得正确的复选框。
// Wire all events into this.
private void AllCheckBoxes_CheckedChanged(Object sender, EventArgs e) {
// Check of the raiser of the event is a checked Checkbox.
// Of course we also need to to cast it first.
if (((RadioButton)sender).Checked) {
// This is the correct control.
RadioButton rb = (RadioButton)sender;
}
}
发布于 2009-11-26 00:09:57
对于那些没有LINQ的用户:
RadioButton GetCheckedRadio(Control container)
{
foreach (var control in container.Controls)
{
RadioButton radio = control as RadioButton;
if (radio != null && radio.Checked)
{
return radio;
}
}
return null;
}
https://stackoverflow.com/questions/1797907
复制相似问题