Search code examples
winformsshowdialog

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


Solution

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