My first question to this forum, so please be kind :D
I'm building a desktop application in C# that should read data from a Raspberry Pi and show it (values, charts...). The MainForm.cs has a menu strip where I can call a child form, ConnectionSetupForm.cs where I can enter the database connection values (db user, password, table, host, port, etc.) which are stored as Properties.Settings.Default.xxx (System.Configuration).
When I'm closing this child form with a save button, I want the MainForm to get this information and refresh. This works, but only after I restart the application, but it should be when the FormClosing or FormClosed event of the child form happens (in my example the MessageBox.Show() never occurs).
What am I missing? I have no errors and no warnings.
MainForm calls the child form ConnectionSetupForm:
private void showConnectionForm(object sender)
{
connectionSetupForm = new ConnectionSetupForm();
connectionSetupForm.MdiParent = this.ParentForm;
connectionSetupForm.StartPosition = FormStartPosition.CenterParent;
connectionSetupForm.ShowDialog();
connectionSetupForm.FormClosed = new FormClosedEventHandler(ConnectionForm_FormClosed);
}
private void ConnectionForm_FormClosed(object sender, FormClosedEventArgs e)
{
Properties.Settings.Default.Save();
Properties.Settings.Default.Reload();
MessageBox.Show("Closed"); // is never called, so this method is never called...
// actually, I want to do some stuff here, e.g.:
this.Text = Properties.Settings.Default.ApplicationName; // name is changed after restart only
connectionSetupForm = null;
}
CodePudding user response:
This looks to be a simple mis-ordering of a couple lines. The connectionSetupForm.ShowDialog(); line is actually a call to a blocking function. This means nothing past this line will execute until AFTER your dialog closes. Because you add the FormClosed event handler after the form has already closed, the ConnectionForm_FormClosed() function never gets called.
Try simply putting the FormClosed event handler before the connectionSetupForm.ShowDialog(); line.
private void showConnectionForm(object sender)
{
connectionSetupForm = new ConnectionSetupForm();
connectionSetupForm.MdiParent = this.ParentForm;
connectionSetupForm.StartPosition = FormStartPosition.CenterParent;
connectionSetupForm.FormClosed = new FormClosedEventHandler(ConnectionForm_FormClosed);
connectionSetupForm.ShowDialog();
}
