其他答案是正确的,但错过了潜在问题的原因。当检查单选按钮时,发送的第一个事件是从未选中的项目的更改,但是如果您通过控件名称检查其状态,您仍将看到其旧的选中状态,因为表单尚未更新。要查看其真实状态,您需要强制转换发送者对象。这允许您在需要时执行与正在取消选择的条件相关的任何操作。
在下面的常见场景中,多个单选按钮被发送到同一个处理程序事件。简单地检查发件人的状态是否已检查在这里不起作用,因为我们需要根据按下的单选按钮执行不同的操作。所以首先我们忽略任何刚刚被取消选中的发件人。然后我们通过控件名称识别检查的发件人以处理正确的操作。
private void ModeChangedExample(object sender, EventArgs e)
{
// multiple radio buttons come here
// We only want to process the checked item.
// if you need to something based on the item which was just unchecked don't use this technique.
// The state of the sender has not been updated yet in the form.
// so checking against rdo_A check state will still show it as checked even if it has just been unchecked
// only the sender variable is up to date at this point.
// To prevent processing the item which has just been uncheked
RadioButton RD = sender as RadioButton;
if (RD.Checked == false) return;
if (rdo_A.Name == RD.Name)
{
//Do stuff
}
if (rdo_B..Name == RD.Name)
{
// Do other stuff
}
if (rdo_C.Name == RD.Name)
{
// Do something else
}
}