Ramon Araujo
Ramon Araujo

Reputation: 1738

Windows Forms method Form.ShowDialog() strange behaviour

I was trying to show a form(FormChild), with some radio buttons in, just to select, close, and get the value of the selected radio button from the calling form(FormParent). On a click event handler for a Button in FormParent, I just did:

var formChild=newFormChild();
formChild.ShowDialog(this);

All was working great until I decided to handle the CheckedChanged event of one of the RadioButtons inside FormChild:

private void SomeRadioButton_CheckedChanged(object sender, EventArgs e)
{
    Close();
}

Now the formChild.ShowDialog(this); did not showed formChild and formChild immediately returns DialogResult.Cancel.

Any explanation on this?

Thanks in advance

Upvotes: 0

Views: 359

Answers (2)

Mark Hall
Mark Hall

Reputation: 54532

The lowest Tab Index radiobutton will be checked by default, If this event handler is assigned to that button it will cause the situation that you are describing.

You can either change your Tab Order or create a Boolean Flag that is set in your Forms Shown EventHandler to keep it from Triggering until you check it again.

public partial class Form1 : Form
{
    bool initDone;
    public Form1()
    {
        InitializeComponent();
    }

    private void radioButton1_CheckedChanged(object sender, EventArgs e)
    {
        if (initDone)
        {
            if (((RadioButton)sender).Checked == true)
            {
                Close();
            }
        }
    }

    private void Form1_Shown(object sender, EventArgs e)
    {
        initDone = true;
    }
}

Upvotes: 2

ImGreg
ImGreg

Reputation: 2983

Is there anywhere if your code that sets the value of the RadioButton? If you programmatically set the "Checked" property of the RadioButton, it will fire the event.

In your situation, the event handler contains your Form.Close() so the form never gets the chance to be visible to the user.

Note: Setting the RadioButton.Checked as "true" in the designer will not fire the event.

Upvotes: 1

Related Questions