In my project, there are two forms frmLogin and frmMain. After successful login from frmLogin I am showing the frmMain form to the user by doing something like this:
In frmLogin form button_click event:
frmMain main = new frmMain();
main.Show();
this.Hide();
In frmMain when the user logs out I want to show the same frmLogin form (not the instance). How to do this?
I tried this code: (creating another instance of frmLogin which I don't want)
In frmMain form button_click event:
if (MessageBox.Show("Do you really want to log out?", "Alert", MessageBoxButtons.YesNo).Equals(DialogResult.Yes))
{
this.FormClosing -= frmMain_FormClosing;
//
Process p = new Process();
p.StartInfo.FileName = Application.ExecutablePath;
p.Start();
//
this.Dispose();
}
I have also tried using internal specifier but no use.
EDIT: As a trainee, I am not allowed to use Static keyword and altering program.cs. If the above approach requires restricted methods (which I have mentioned) then please suggest me an alternate approach.
Pass a frmLogin reference to frmMain. Then, just before you dispose of frmMain, show frmLogin.
frmMain main = new frmMain();
main.LoginForm = this;
main.Show();
this.Hide();
Then in the button click event:
if (MessageBox.Show("Do you really want to log out?", "Alert", MessageBoxButtons.YesNo).Equals(DialogResult.Yes))
{
this.FormClosing -= frmMain_FormClosing;
LoginForm.Show();
this.Dispose();
}
All what you have to do is assign login page as owner of nextform to be opened
In your login Page call following function where you want to open nextForm
void openNextForm()
{
Form f2 = new YourForm();
f2.owner=this;
f2.Show();
this.Hide();
}
In your nextForm (e.g mainForm) write following aginst your button click
void ButtonLogOut_Click(object sender, EventArgs e)
{
this.Owner.Show();
this.Hide();
this.Dispose();
}
I think the cleanest approach when dealing with multiple forms is to create them in Program.cs, and keep all the methods to manage them there, then call those methods from event handlers. Kind of like this:
static class Program
{
public static MainForm mainForm = new MainForm();
public static LoginForm loginForm = new LoginForm();
[STAThread]
static void Main()
{
mainForm.Hide();
loginForm.Hide();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(loginForm);
}
public static void Login()
{
loginForm.Hide();
mainForm.Show();
// probably do more here
}
public static void Logout()
{
if (MessageBox.Show("Do you really want to log out?", "Alert", MessageBoxButtons.YesNo).Equals(DialogResult.Yes)))
{
mainForm.Hide();
loginForm.Show();
// probably do more here
}
}
}
Then in event handlers you can just call Program.Login() or Program.Logout()
I don't get why you don't use the ShowDialog() method?
frmMain main = new frmMain();
this.Hide();
main.ShowDialog();
this.Show();
The login form will be hidden and after the main form is closed, the login form's execution will continue and it will be automatically shown...
Related
I'm searching for the proper way how to open and switch forms some uses Application.Run( new Form1());, some uses Form1.ShowDialog(); and Form.Show();. I really want to know how to properly pass a data from a form into another using constructors.
Additionally I want to know why when I use Form.Close(); to close to current form before to open next form .... both forms closes.
Here are my codes.
try
{
Form2 f2 = new Form2(connection, userLogin);
this.Hide();
f2.ShowDialog();
}
catch (NullReferenceException nre) {
MessageBox.Show("Sorry Login Another User account");
}
What I'm trying to do here is to pass the MySqlConnection in the variable connection and the valid user in the variable userLogin into the Form2. This method works but I'm not sure if this the right way to do it.
Here are the codes in Form2.
public partial class Form2 : Form
{
MySqlConnection connection;
User activeUser;
public Form2(MySqlConnection pConn, User loginUser)
{
InitializeComponent();
connection = pConn;
activeUser = loginUser;
this.Init();
this.CenterToScreen();
}
private void logoutB_Click(object sender, EventArgs e)
{
this.Hide();
new Form1().Visible = false;
new Form1().ShowDialog();
//Application.Run(new Form1());
}
}
Showing the Form2 doesn't also have a problem but when the logout button is pressed.
Form that is already visible cannot be displayed as a modal dialog box.
Set the form's visible property to false before calling showDialog.
It says Form already visible? So does it mean the form is still open even though I used this.Hide();? and when I use the code Application.Run(new Form1());
Starting a second message loop on a single thread is not a valid operation.
Use Form.ShowDialog instead.
In this section of code:
new Form1().Visible = false;
new Form1().ShowDialog();
You are simply creating two new forms; you are creating a form in the first line with Visibilityproperty set to false; and in the second line you are creating a new Form and calling ShowDialog on it. So two instances are not the same.
this.Hide();
Form1 a = new Form1();
a.Visible = false;
a.ShowDialog();
Since you use ShowDialog to show Form2 from Form1, then simply close the second form when the user clicks the logout button.
private void logoutB_Click(object sender, EventArgs e)
{
this.Close();
}
This will bring execution back to Form1 right after the ShowDialog call. So, make sure then you re-show the form after you invoke ShowDialog like this:
try
{
Form2 f2 = new Form2(connection, userLogin);
this.Hide(); //hide my self
f2.ShowDialog(); //show Form2.
//Execution will resume here after Form2 is closed
this.Show(); //re-show my self
}
catch (NullReferenceException nre)
{
MessageBox.Show("Sorry Login Another User account");
}
I have two forms in my project (Login and Main).
What I'm trying to accoomplish is, if the login is successful, I must show the Main form and close the Login form.
I have this method in Login form that closes the Login form when the login is successful. But the Main form doesn't show.
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
var main = new Main();
main.Show();
this.Close();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
I tried hiding the Login form if the login process is successful. But it bothers me because I know while my program is running the login form is still there too, it should be closed right?
What should be the right approach for this?
Thanks...
The reason your main form isn't showing is because once you close the login form, your application's message pump is shut down, which causes the entire application to exit. The Windows message loop is tied to the login form because that's the one you have set as the startup form in your project properties. Look in your "Program.cs" file, and you'll see the responsible bit of code: Application.Run(new LoginForm()). Check out the documentation for that method here on MSDN, which explains this in greater detail.
The best solution is to move the code out of your login form into the "Program.cs" file. When your program first starts, you'll create and show the login form as a modal dialog (which runs on a separate message loop and blocks execution of the rest of your code until it closes). When the login dialog closes, you'll check its DialogResult property to see if the login was successful. If it was, you can start the main form using Application.Run (thus creating the main message loop); otherwise, you can exit the application without showing any form at all. Something like this:
static void Main()
{
LoginForm fLogin = new LoginForm();
if (fLogin.ShowDialog() == DialogResult.OK)
{
Application.Run(new MainForm());
}
else
{
Application.Exit();
}
}
I would do this the other way round.
In the OnLoad event for your Main form show the Logon form as a dialog. If the dialog result of that is OK then allow Main to continue loading, if the result is authentication failure then abort the load and show the message box.
EDIT Code sample(s)
private void MainForm_Load(object sender, EventArgs e)
{
this.Hide();
LogonForm logon = new LogonForm();
if (logon.ShowDialog() != DialogResult.OK)
{
//Handle authentication failures as necessary, for example:
Application.Exit();
}
else
{
this.Show();
}
}
Another solution would be to show the LogonForm from the Main method in program.cs, something like this:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
LogonForm logon = new LogonForm();
Application.Run(logon);
if (logon.LogonSuccessful)
{
Application.Run(new MainForm());
}
}
In this example your LogonForm would have to expose out a LogonSuccessful bool property that is set to true when the user has entered valid credentials
This is my solution. Create ApplicationContext to set mainform of application and change mainform when you want to open new form and close current form.
Program.cs
static class Program
{
static ApplicationContext MainContext = new ApplicationContext();
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainContext.MainForm = new Authenticate();
Application.Run(MainContext);
}
public static void SetMainForm(Form MainForm)
{
MainContext.MainForm = MainForm;
}
public static void ShowMainForm()
{
MainContext.MainForm.Show();
}
}
When login process is complete.
private void BtLogin_Click(object sender, EventArgs e)
{
//Login Process Here.
Program.SetMainForm(new Portal());
Program.ShowMainForm();
this.Close();
}
I hope this will help you.
It's simple.
Here is the code.
private void button1_Click(object sender, EventArgs e)
{
//creating instance of main form
MainForm mainForm = new MainForm();
// creating event handler to catch the main form closed event
// this will fire when mainForm closed
mainForm.FormClosed += new FormClosedEventHandler(mainForm_FormClosed);
//showing the main form
mainForm.Show();
//hiding the current form
this.Hide();
}
// this is the method block executes when main form is closed
void mainForm_FormClosed(object sender, FormClosedEventArgs e)
{
// here you can do anything
// we will close the application
Application.Exit();
}
This is the most elegant solution.
private void buttonLogin_Click(object sender, EventArgs e)
{
MainForm mainForm = new MainForm();
this.Hide();
mainForm.ShowDialog();
this.Close();
}
;-)
Here's a simple solution, your problem is that your whole application closes when your login form closes right? If so, then go to your projects properties and on the Application Tab change the shutdown mode to "When last form closes" that way you can use Me.close without closing the whole program
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Login();
}
private static bool logOut;
private static void Login()
{
LoginForm login = new LoginForm();
MainForm main = new MainForm();
main.FormClosed += new FormClosedEventHandler(main_FormClosed);
if (login.ShowDialog(main) == DialogResult.OK)
{
Application.Run(main);
if (logOut)
Login();
}
else
Application.Exit();
}
static void main_FormClosed(object sender, FormClosedEventArgs e)
{
logOut= (sender as MainForm).logOut;
}
}
public partial class MainForm : Form
{
private void btnLogout_ItemClick(object sender, ItemClickEventArgs e)
{
//timer1.Stop();
this.logOut= true;
this.Close();
}
}
I think a much better method is to do this in the Program.cs file where you usually have Application.Run(form1), in this way you get a cleaner approach, Login form does not need to be coupled to Main form, you simply show the login and if it returns true you display the main form otherwise the error.
Try this:
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
this.Close();
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(Main));
t.Start();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
[STAThread]
public void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
You must call the new form in a diferent thread apartment, if I not wrong, because of the call system of windows' API and COM interfaces.
One advice: this system is high insecure, because you can change the if condition (in MSIL) and it's "a children game" to pass out your security. You need a stronger system to secure your software like obfuscate or remote login or something like this.
Hope this helps.
you should do it the other way round:
Load the mainform first and in its onload event show your loginform with showdialog() which will prevent mainform from showing until you have a result from the loginform
EDIT:
As this is a login form and if you do not need any variables from your mainform (which is bad design in practice), you should really implement it in your program.cs as Davide and Cody suggested.
best way for show login for and close login form before login successfully put login form in FrmMain after InitializeComponent.
public FrmMain()
{
FrmSplash FrmSplash = new FrmSplash();
FrmSplash.ShowDialog();
InitializeComponent();
//Login Section
{
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
this.Hide();
var main = new Main();
main.Show();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
try this
private void cmdLogin_Click(object sender, EventArgs e)
{
if (txtUserName.Text == "admin" || txtPassword.Text == "1")
{
FrmMDI mdi = new FrmMDI();
mdi.Show();
this.Hide();
}
else {
MessageBox.Show("Incorrect Credentials", "Library Management System", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
and when you exit the Application you can use
Application.Exit();
Evan the post is too old i like to give you a trick to do this if you wants to show splash/login screen and when the progress bar of splash screen get certain value/or successful login happen and closed the splash/login then re show the main form, frm-main will be the startup form not frm-spalash
in frm-main
public partial class frmMain : Form
{
public frmMain()
{
frmSplash frm = new frmSplash();
frm.Show(); // new splash screen will shows
this.Opacity=0; // will hide your main form
InitializeComponent();
}
}
in the frm-Splash
private void timer1_Tick(object sender, EventArgs e)
{
int cnt = progressBar1.Value;
switch (cnt)
{
case 0:
//Do sum stuff
break;
case 100:
this.Close(); //close the frm-splash
frmMain.ActiveForm.Opacity = 100; // show the frm-main
break;
}
progressBar1.Value = progressBar1.Value+1;
}
if you use it for login form
private void btlogin_Click(object sender, EventArgs e)
{
bool login = false;
//try your login here
//connect your database or whatever
//and then when it success update login variable as true
if(login == true){
this.Close(); //close the frm-login
frmMain.ActiveForm.Opacity = 100; // show the frm-main
}else{
//inform user about failed login
}
}
note that i use a timer and a progress bar to manipulate the actions you don't need those two it just for sake of complete answer only, hope this helps
1.Go to MainMenu Design properties> Go to my events
2.Click MainMenu event Shown and show LoginForm
3.Leave MainMenu as the First run in Program.cs
I'm creating a login function. After validating the password, the main form will be called.
Here is the partial code:
Login.cs
private void btnLogin_Click(object sender, EventArgs e)
{
//Interaction with Database
Main.Show();
this.Close();
}
As I expect only the Login form will be closed and the Main form will remain unchanged.
However both of them are closed after the last command is executed.
How can I fix this problem please ?
In your program.cs put in Application.Run(main);
Then in main.load event open your login form using show dialog.
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
and on main
public Main()
{
InitializeComponent();
Login p = new Login();
DialogResult dr = p.ShowDialog();
if (dr == DialogResult.OK)
{
//...
}
else
Application.Exit();
}
If you close your main Form, application terminates. Instead of closing, you can hide your main Form with :
this.Hide();
private void btnLogin_Click(object sender, EventArgs e)
{
// hide main form
this.Hide();
// show other form
Form2 form2 = new Form2();
form2.Show();
// close application
this.Close();
}
If you open the Program.cs file you will see a command similar to this:
Application.Run(new PasswordForm());
The form specified in this command is what ties the program into existence, when this form closes the STA Thread continues execution and then finishes, closing the whole application.
To fix this, create an instance of you password form and do all that in the Program.cs file before calling Application.Run on the main UI form.
I have two forms in my project (Login and Main).
What I'm trying to accoomplish is, if the login is successful, I must show the Main form and close the Login form.
I have this method in Login form that closes the Login form when the login is successful. But the Main form doesn't show.
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
var main = new Main();
main.Show();
this.Close();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
I tried hiding the Login form if the login process is successful. But it bothers me because I know while my program is running the login form is still there too, it should be closed right?
What should be the right approach for this?
Thanks...
The reason your main form isn't showing is because once you close the login form, your application's message pump is shut down, which causes the entire application to exit. The Windows message loop is tied to the login form because that's the one you have set as the startup form in your project properties. Look in your "Program.cs" file, and you'll see the responsible bit of code: Application.Run(new LoginForm()). Check out the documentation for that method here on MSDN, which explains this in greater detail.
The best solution is to move the code out of your login form into the "Program.cs" file. When your program first starts, you'll create and show the login form as a modal dialog (which runs on a separate message loop and blocks execution of the rest of your code until it closes). When the login dialog closes, you'll check its DialogResult property to see if the login was successful. If it was, you can start the main form using Application.Run (thus creating the main message loop); otherwise, you can exit the application without showing any form at all. Something like this:
static void Main()
{
LoginForm fLogin = new LoginForm();
if (fLogin.ShowDialog() == DialogResult.OK)
{
Application.Run(new MainForm());
}
else
{
Application.Exit();
}
}
I would do this the other way round.
In the OnLoad event for your Main form show the Logon form as a dialog. If the dialog result of that is OK then allow Main to continue loading, if the result is authentication failure then abort the load and show the message box.
EDIT Code sample(s)
private void MainForm_Load(object sender, EventArgs e)
{
this.Hide();
LogonForm logon = new LogonForm();
if (logon.ShowDialog() != DialogResult.OK)
{
//Handle authentication failures as necessary, for example:
Application.Exit();
}
else
{
this.Show();
}
}
Another solution would be to show the LogonForm from the Main method in program.cs, something like this:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
LogonForm logon = new LogonForm();
Application.Run(logon);
if (logon.LogonSuccessful)
{
Application.Run(new MainForm());
}
}
In this example your LogonForm would have to expose out a LogonSuccessful bool property that is set to true when the user has entered valid credentials
This is my solution. Create ApplicationContext to set mainform of application and change mainform when you want to open new form and close current form.
Program.cs
static class Program
{
static ApplicationContext MainContext = new ApplicationContext();
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainContext.MainForm = new Authenticate();
Application.Run(MainContext);
}
public static void SetMainForm(Form MainForm)
{
MainContext.MainForm = MainForm;
}
public static void ShowMainForm()
{
MainContext.MainForm.Show();
}
}
When login process is complete.
private void BtLogin_Click(object sender, EventArgs e)
{
//Login Process Here.
Program.SetMainForm(new Portal());
Program.ShowMainForm();
this.Close();
}
I hope this will help you.
It's simple.
Here is the code.
private void button1_Click(object sender, EventArgs e)
{
//creating instance of main form
MainForm mainForm = new MainForm();
// creating event handler to catch the main form closed event
// this will fire when mainForm closed
mainForm.FormClosed += new FormClosedEventHandler(mainForm_FormClosed);
//showing the main form
mainForm.Show();
//hiding the current form
this.Hide();
}
// this is the method block executes when main form is closed
void mainForm_FormClosed(object sender, FormClosedEventArgs e)
{
// here you can do anything
// we will close the application
Application.Exit();
}
This is the most elegant solution.
private void buttonLogin_Click(object sender, EventArgs e)
{
MainForm mainForm = new MainForm();
this.Hide();
mainForm.ShowDialog();
this.Close();
}
;-)
Here's a simple solution, your problem is that your whole application closes when your login form closes right? If so, then go to your projects properties and on the Application Tab change the shutdown mode to "When last form closes" that way you can use Me.close without closing the whole program
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Login();
}
private static bool logOut;
private static void Login()
{
LoginForm login = new LoginForm();
MainForm main = new MainForm();
main.FormClosed += new FormClosedEventHandler(main_FormClosed);
if (login.ShowDialog(main) == DialogResult.OK)
{
Application.Run(main);
if (logOut)
Login();
}
else
Application.Exit();
}
static void main_FormClosed(object sender, FormClosedEventArgs e)
{
logOut= (sender as MainForm).logOut;
}
}
public partial class MainForm : Form
{
private void btnLogout_ItemClick(object sender, ItemClickEventArgs e)
{
//timer1.Stop();
this.logOut= true;
this.Close();
}
}
I think a much better method is to do this in the Program.cs file where you usually have Application.Run(form1), in this way you get a cleaner approach, Login form does not need to be coupled to Main form, you simply show the login and if it returns true you display the main form otherwise the error.
Try this:
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
this.Close();
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(Main));
t.Start();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
[STAThread]
public void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
You must call the new form in a diferent thread apartment, if I not wrong, because of the call system of windows' API and COM interfaces.
One advice: this system is high insecure, because you can change the if condition (in MSIL) and it's "a children game" to pass out your security. You need a stronger system to secure your software like obfuscate or remote login or something like this.
Hope this helps.
you should do it the other way round:
Load the mainform first and in its onload event show your loginform with showdialog() which will prevent mainform from showing until you have a result from the loginform
EDIT:
As this is a login form and if you do not need any variables from your mainform (which is bad design in practice), you should really implement it in your program.cs as Davide and Cody suggested.
best way for show login for and close login form before login successfully put login form in FrmMain after InitializeComponent.
public FrmMain()
{
FrmSplash FrmSplash = new FrmSplash();
FrmSplash.ShowDialog();
InitializeComponent();
//Login Section
{
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
this.Hide();
var main = new Main();
main.Show();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
try this
private void cmdLogin_Click(object sender, EventArgs e)
{
if (txtUserName.Text == "admin" || txtPassword.Text == "1")
{
FrmMDI mdi = new FrmMDI();
mdi.Show();
this.Hide();
}
else {
MessageBox.Show("Incorrect Credentials", "Library Management System", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
and when you exit the Application you can use
Application.Exit();
Evan the post is too old i like to give you a trick to do this if you wants to show splash/login screen and when the progress bar of splash screen get certain value/or successful login happen and closed the splash/login then re show the main form, frm-main will be the startup form not frm-spalash
in frm-main
public partial class frmMain : Form
{
public frmMain()
{
frmSplash frm = new frmSplash();
frm.Show(); // new splash screen will shows
this.Opacity=0; // will hide your main form
InitializeComponent();
}
}
in the frm-Splash
private void timer1_Tick(object sender, EventArgs e)
{
int cnt = progressBar1.Value;
switch (cnt)
{
case 0:
//Do sum stuff
break;
case 100:
this.Close(); //close the frm-splash
frmMain.ActiveForm.Opacity = 100; // show the frm-main
break;
}
progressBar1.Value = progressBar1.Value+1;
}
if you use it for login form
private void btlogin_Click(object sender, EventArgs e)
{
bool login = false;
//try your login here
//connect your database or whatever
//and then when it success update login variable as true
if(login == true){
this.Close(); //close the frm-login
frmMain.ActiveForm.Opacity = 100; // show the frm-main
}else{
//inform user about failed login
}
}
note that i use a timer and a progress bar to manipulate the actions you don't need those two it just for sake of complete answer only, hope this helps
1.Go to MainMenu Design properties> Go to my events
2.Click MainMenu event Shown and show LoginForm
3.Leave MainMenu as the First run in Program.cs
I have form which is opened using ShowDialog Method. In this form i have a Button called More.
If we click on More it should open another form and it should close the current form.
on More Button's Click event Handler i have written the following code
MoreActions objUI = new MoreActions ();
objUI.ShowDialog();
this.Close();
But what is happening is, it's not closing the first form. So, i modified this code to
MoreActions objUI = new MoreActions ();
objUI.Show();
this.Close();
Here, The second form is getting displayed and within seconds both the forms getting closed.
Can anybody please help me to fix issue. What i need to do is, If we click on More Button, it should open another form and close the first form.
Any kind of help will be really helpful to me.
In my opinion the main form should be responsible for opening both child form. Here is some pseudo that explains what I would do:
// MainForm
private ChildForm childForm;
private MoreForm moreForm;
ButtonThatOpenTheFirstChildForm_Click()
{
childForm = CreateTheChildForm();
childForm.MoreClick += More_Click;
childForm.Show();
}
More_Click()
{
childForm.Close();
moreForm = new MoreForm();
moreForm.Show();
}
You will just need to create a simple event MoreClick in the first child. The main benefit of this approach is that you can replicate it as needed and you can very easily model some sort of basic workflow.
If I got you right, are you trying like this?
into this?
in your Form1, add this event in your button:
// button event in your Form1
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog(); // Shows Form2
}
then, in your Form2 add also this event in your button:
// button event in your Form2
private void button1_Click(object sender, EventArgs e)
{
Form3 f3 = new Form3(); // Instantiate a Form3 object.
f3.Show(); // Show Form3 and
this.Close(); // closes the Form2 instance.
}
ok so I used this:
public partial class Form1 : Form
{
private void Button_Click(object sender, EventArgs e)
{
Form2 myForm = new Form2();
this.Hide();
myForm.ShowDialog();
this.Close();
}
}
This seems to be working fine but the first form is just hidden and it can still generate events. the "this.Close()" is needed to close the first form but if you still want your form to run (and not act like a launcher) you MUST replace it with
this.Show();
Best of luck!
I would use a value that gets set when more button get pushed closed the first dialog and then have the original form test the value and then display the the there dialog.
For the Ex
Create three windows froms
Form1 Form2 Form3
Add One button to Form1
Add Two buttons to form2
Form 1 Code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool DrawText = false;
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog();
if (f2.ShowMoreActions)
{
Form3 f3 = new Form3();
f3.ShowDialog();
}
}
Form2 code
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public bool ShowMoreActions = false;
private void button1_Click(object sender, EventArgs e)
{
ShowMoreActions = true;
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
Leave form3 as is
Try this..
//button1 will be clicked to open a new form
private void button1_Click(object sender, EventArgs e)
{
this.Visible = false; // this = is the current form
SignUp s = new SignUp(); //SignUp is the name of my other form
s.Visible = true;
}
private void Button1_Click(object sender, EventArgs e)
{
NewForm newForm = new NewForm(); //Create the New Form Object
this.Hide(); //Hide the Old Form
newForm.ShowDialog(); //Show the New Form
this.Close(); //Close the Old Form
}
you may consider this example
//Form1 Window
//EventHandler
Form1 frm2 = new Form1();
{
frm2.Show(this); //this will show Form2
frm1.Hide(); //this Form will hide
}
For example, you have a Button named as Button1. First click on it it will open the EventHandler of that Button2 to call another Form you should write the following code to your Button.
your name example=form2.
form2 obj=new form2();
obj.show();
To close form1, write the following code:
form1.visible=false;
or
form1.Hide();
You could try adding a bool so the algorithm would know when the button was activated. When it's clicked, the bool checks true, the new form shows and the last gets closed.
It's important to know that forms consume some ram (at least a little bit), so it's a good idea to close those you're not gonna use, instead of just hiding it. Makes the difference in big projects.
You need to control the opening of sub forms from a main form.
In my case I'm opening a Login window first before I launch my form1. I control everything from Program.cs. Set up a validation flag in Program.cs. Open Login window from Program.cs. Control then goes to login window. Then if the validation is good, set the validation flag to true from the login window. Now you can safely close the login window. Control returns to Program.cs. If the validation flag is true, open form1. If the validation flag is false, your application will close.
In Program.cs:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///
//Validation flag
public static bool ValidLogin = false;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Login());
if (ValidLogin)
{
Application.Run(new Form1());
}
}
}
In Login.cs:
private void btnOK_Click(object sender, EventArgs e)
{
if (txtUsername.Text == "x" && txtPassword.Text == "x")
{
Program.ValidLogin = true;
this.Close();
}
else
{
MessageBox.Show("Username or Password are incorrect.");
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
Use this.Hide() instead of this.Close()
Do this to Program.cs
using System;
namespace ProjectName
{
public class Program
{
[STAThread]
public static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetDefaultCompatibleTextRendering(false);
new Form1().Show();
Application.Run();
}
}
}