C#RadioButton无法正常工作

时间:2015-04-22 07:36:07

标签: c# radio-button

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“RadioButton_1Storey”将在RadioButton_2Storey开始执行之前再执行1次。和副Versa

2 个答案:

答案 0 :(得分:2)

当您点击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();
    }
};

答案 1 :(得分:1)

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

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) 
{
    ... 
}