繁体   English   中英

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次。 和副Versa

当您单击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) 
{
    ... 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM