Reputation: 608
I have 2 forms Form1 and Form2, when program executes I want both forms to display but Form2 with ShowDialog();
i.e user has to respond to Form2 before using Form1. How can I achieve this?
Form2 will take userinput and will display on Form1, so do I have to hide Form2 after user responds to Form2 or just kill it.
Upvotes: 0
Views: 80
Reputation: 45119
I would do this in a form like this:
public FormMain()
{
InitializeComponent();
//Visible should be set within InitializeComponent (or Designer)
Visible = false;
//Can't be done in constructor, or this.Close()
//would lead to an exception.
this.Load += (sender, e) =>
{
bool loginSuccessfull = false;
using (var loginScreen = new FormLogin())
{
if (DialogResult.OK == loginScreen.ShowDialog())
{
//Maybe some other public function from loginScreen
//is needed to determine if the login was successfull
//loginSuccessfull = loginScreen.CheckCredentials();
loginSuccessfull = true;
}
}
if (loginSuccessfull)
{
Visible = true;
}
else
{
this.Close();
}
};
}
Upvotes: 1
Reputation: 1503449
If you use ShowDialog
, Form2 will automatically be hidden when hits OK or Cancel (assuming you've set the DialogResult
property for any relevant buttons) but you will still need to dispose of it. You can do something like this:
using (Form f2 = new Form2())
{
// Populate it with existing data
DialogResult result = f2.ShowDialog();
// Use the result and any data within f2
}
Upvotes: 3