C# RadioButton 不能正常工作

C# RadioButton not Working Properly

private void SelectingNumberOfStorey()
{
    RadioButton_1Storey.CheckedChanged += (sender, args) =>
    {
        NumberOfStorey = 1;
        HidingFirstQuestions();
    };

    RadioButton_2Storey.CheckedChanged += (sender, args) =>
    {
        NumberOfStorey = 2;
        HidingFirstQuestions();
    };

    if (Runner == "Must Run")
    {
        AddCheckBox();
        AddGrid();
    }
}

private void HidingFirstQuestions()
{
    DialogResult dialogResult = MessageBox.Show("You Select " + NumberOfStorey + " Storey!", "Selection", MessageBoxButtons.OKCancel);

    if (dialogResult == DialogResult.OK)
    {
        Runner = "Must Run";
    }
    else if (dialogResult == DialogResult.Cancel)
    {
        //do nothing
    }
}

如果我第一次单击 RadioButton_1Storey 并在消息框中单击取消,它就可以正常工作。但是当我点击 RadioButton_2Storey 然后取消时,之前的单选按钮 "RadioButton_1Storey" 将在 RadioButton_2Storey 开始执行之前再执行 1 次。反之亦然

当您单击 RadioButton_2Storey 时,RadioButton_1Storey.Checked 变为 false,引发 CheckedChanged 事件并且 HidingFirstQuestions 运行

像这样修改事件处理程序

RadioButton_1Storey.CheckedChanged += (sender, args) =>
{
    if (RadioButton_1Storey.Checked)
    {
      NumberOfStorey = 1;
      HidingFirstQuestions();
    }
};

RadioButton_2Storey.CheckedChanged += (sender, args) =>
{
    if (RadioButton_2Storey.Checked)
    {
      NumberOfStorey = 2;
      HidingFirstQuestions();
    }
};

为了确保您的代码没有被调用两次,我将其更改为:

private void SelectingNumberOfStorey()
{
     RadioButton_1Storey.CheckedChanged -= RadioButton_1StoreyCheckedChanged;
     RadioButton_1Storey.CheckedChanged += RadioButton_1StoreyCheckedChanged;

     RadioButton_2Storey.CheckedChanged -= RadioButton_2StoreyCheckedChanged;
     RadioButton_2Storey.CheckedChanged += RadioButton_2StoreyCheckedChanged;

     ... 
}

private void RadioButton_1StoreyCheckedChanged(object sender, EventArgs args) 
{
    ... 
}

private void RadioButton_2StoreyCheckedChanged(object sender, EventArgs args) 
{
    ... 
}