Son Gozita
Son Gozita

Reputation: 67

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

Upvotes: 0

Views: 166

Answers (2)

stefankmitph
stefankmitph

Reputation: 3306

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

Upvotes: 1

ASh
ASh

Reputation: 35733

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();
    }
};

Upvotes: 2

Related Questions