简体   繁体   中英

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
    }
}

If I will clicked the RadioButton_1Storey and clicked cancel in messagebox for the first time, it works just fine. But when I clicked RadioButton_2Storey then cancel, the previous radiobutton "RadioButton_1Storey" will execute 1 more time before the RadioButton_2Storey start executing. And Vice Versa

when you click RadioButton_2Storey, RadioButton_1Storey.Checked becomes false , and raise CheckedChanged event and HidingFirstQuestions runs

modify event handlers like this

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

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

just to be sure that your code isn't called twice, I'd change it to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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