Home > OS >  Close a form then do a action in another forme
Close a form then do a action in another forme

Time:02-26

I have two form's, MainForm and Config, when my software opens, MainForm is opened and Config form is opened too.

public mainForm()
{
    InitializeComponent();

    this.Show();

    connectionStatusToolStrip.Text = "**********";
    connectionStatusToolStrip.BackColor = Color.Red;
    statusConnection = false;

    tryConnect = true;

    Config config = new Config();
    config.ShowDialog();
}

I'm showing the Config form as a Dialog, for focus reasons.

When I close the Config form, I need to refresh or something like that, the MainForm.

Here is the code from the "Ok" button on the Config form.

private void ok_button(object sender, EventArgs e)
{
    mainForm.USER_FTP = UsuerConfigTextBox.Text.ToString();
    mainForm.PASSWORD_FTP = PasswordConfigTextBox.Text.ToString();
    mainForm.IP_CONNECTION = IpConfigTextBox.Text.ToString();

    this.Close();
}

CodePudding user response:

Probably better to flip it round:

public mainForm()
{
    InitializeComponent();

    this.Show();

    connectionStatusToolStrip.Text = "**********";
    connectionStatusToolStrip.BackColor = Color.Red;
    statusConnection = false;

    tryConnect = true;

    Config config = new Config();
    var r = config.ShowDialog();
    if(r == DialogResult.OK){
        USER_FTP = config.UsuerConfigTextBox.Text;
        PASSWORD_FTP = config.PasswordConfigTextBox.Text;
        IP_CONNECTION = config.IpConfigTextBox.Text;

        //connect to server?
    }
}

You'd need to make the user/pass/ip textboxes public, or provide properties that get their values:

partial class Config: Form{

  public string UserName => UsuerConfigTextBox.Text;
  ...

}


...


if(r == DialogResult.OK){
    USER_FTP = config.UserName;
    ...

    //connect to server?
}

This way your ConfigForm doesn't need to know about MianForm's existance at all: Mainform makes the config form, shows it, waits for it to close and pulls the data from it. ConfigForm can be reused in another project that doesn't even have a MainForm class..

CodePudding user response:

You're looking at this backwards. The config dialog should not try to update the main form. Instead, it should just expose the configuration data via public methods/properties.

Since ShowDialog blocks, you can then just query the config form object after it returns for the data:

Config config = new Config();
config.ShowDialog();

var ftpUser = config.FTPUser;
var pwd = config.FTPPwd;
var addr = config.FTPAddr

On another note, I would not be performing blocking work in a constructor like that. Using the 'OnShown' event is a better place.

  • Related