C# Switching forms with passed data in the constructor - c#

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");
}

Related

ObjectDisposedException when opening a form

Everything works as it should when I open the form the first time with Form.show(); but after I close it with Form.Close(); and try to re-open it I get a 'ObjectDisposedException'. What do I need to do to avoid this if I need to open the form for more than one time?
You will need to instantiate a new Form after closing and disposing of the existing instance.
Form form = new Form();
form.Show();
You can use
form.Hide();
this wil just hide the form from the user instead of disposing it.
Keep in mind that if the user closes the form, it again will be disposed, so you could prevent that with
public Form()
{
InitializeComponent();
this.FormClosing += Form_FormClosing;
}
private void Form_FormClosing(object sender, FormClosingEventArgs e)
{
this.Hide();
e.Cancel = true;
}

how to open a form from another form in c#

i am writing a code for serial key registration.
if the serial key entered by the user is correct then anothr form must open and the present form must close.
please go thought the code.
namespace ExtTrigger
{
public partial class Activation : Form
{
public Activation()
{
InitializeComponent();
}
private void ActivateButton_Click(object sender, EventArgs e)
{
String key;
key = string.Concat(textBox1.Text,textBox2.Text,textBox3.Text,textBox4.Text);
if (key == "1234123412341234")
{
Properties.Settings.Default.Registered = true;
MessageBox.Show("hurray", "", MessageBoxButtons.OK);
Form1 f1= new Form1();
f1.ShowDialog();
this.Close();
}
else
MessageBox.Show("No Match", "", MessageBoxButtons.OK);
}
private void Activation_Load(object sender, EventArgs e)
{
}
}
my problem is: On clicking on ActivateBotton, Form1 opens but the present form doesnot close.
i have read in few threads that in VB we can change the property: ShutdownMode.
How can we do that in c#?
f1.ShowDialog(); blocks the call, it doesn't go to the next line until that new form has been closed.
An option would be to use:
f1.Show();
Show doesn't block the call, it passes to the next statement. It will not wait for the new form to be closed.
since you have show the second form as f1.ShowDialog() so first one remain open untile second one close, try this
Form1 f1= new Form1();
f1.Show();
this.Close();
The following code should do the trick:
using(Form1 f1 = new Form1())
{
this.Hide();
DialogResult result = f1.ShowDialog();
if(result == DialogResult.OK)
{
this.Show();
}
}
You create your new form within the using-block, then you hide your main form(or the form you are in at the moment) create a DialogResult that gets set by the newly opened form and open this form. Now you can set the results you want to check for inside of your new form and if everything went well inside of you new form you set the DialogResult to OK via:
this.DialogResult = DialogResult.OK;
Now back in our first form you check for the DialogResult and if it is okay you show your main form again. If it was not okay you could just reopen the 2nd form and let the user try again.
Opening a new form is very simple, but the way you do it really depends on your need.
Case 1: I would like to freeze/ block the calling form on secondary form call
In this case you should be using secondaryFormObj.ShowDialog();
Of course, when using this technique your called form, which now acts as a dialog, should "return" an answer to its caller parent on closure.
For example:
private void SecondaryForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Just a dummy code example.
// Always returns Yes result on form closure
this.DialogResult = System.Windows.Forms.DialogResult.Yes;
}
For more help and examples on this manner you can use MSDN:
DialogResult - MSDN
Case 2: I would like to have both forms responding at the same time
In this case you basically need to call secondaryFormObj.Show();
If you want the caller form to be hidden on secondary form call, just
invoke this.Hide();
after the call to secondaryFormObj.Show(); in the caller class.
You can also close the caller form using this.Close(); as long as the caller form is not the application's main form.
... And remember
Always make sure you initialized the secondary form object before
invoking it with either secondaryFormObj.Show(); or
secondaryFormObj.ShowDialog();
Initializing a form is done the same way like every typical object using the
new operator.
For example: secondaryFormObj = new Form();
Hopes this helps. Happy coding!

How to go back to the previous form with no loss of data

I have a first form where the user designs a hotel for himself/herself. After clicking on a created room from the created floor, the user introduces information to a second form which opens from the first form in order to reserve that room. When a button is clicked on the second form the form should disappear sending the data to the first form then save it to a file in the first form.
My issue is that when I am trying to hide or to close the second form, it either exits the application or it just hides the tab.
Could anyone tell me how to close the second form an get back to the first form without losing any data, any buttons, any text or any information example in a combo box.
Code wise that is what I have in the Program.cs:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 myStart = new Form1();
if (myStart.ShowDialog() == DialogResult.OK)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
else
{
Application.Exit();
}
}
And that is what I tried to put in the button that closes the second form, but it does not work :
Form2Reservations f2 = new Form2Reservations();
f2.Close();
and I also tried :
var main = new Form1();
main.Show();
main.BringToFront(); , but it gives me a new Form1 and I do not want to lose everything that I already had in Form1.
and I also tried this.Close(); and this.Hide(); , but the first one closes the whole application and the second one just puts both tabs on the toolbar.
Also, I am a beginner in C#, I have not taken any University level courses, I am just self-teaching myself with the help of the internet and tutorials.
Thank you.
SECOND EDIT:
When I open up my second form I use this code in form 1:
Form2Reservations f2 = new Form2Reservations();
f2.receiveDataFromForm1(typeOfRoom, numberOfTheRoom, floor);
f2.ShowDialog();
this.Hide();
The edited changeRoom_Click looks like this :
private void changeRoomButton_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
And the Program.cs code with static void Main() still looks the same.
My idea is the following : Is there any chance that I am not opening the second form correctly, so when I want to close the second form, it closes both of them, because somehow they are closely connected and this.Close() is referring to both forms ? Is that possible ? Would my mistake be in the first form when I call the opening of the second form ?
You are checking if the DialogResult is set on 'OK'. But you aren't setting the DialogResult before Closing the form, which is why it will return False on the If statement and exits the application.
You need to add
this.DialogResult = System.Windows.Forms.DialogResult.OK;
before closing the Form in changeRoomButton_Click.
--EDIT:
Lets give it another try.
You are calling receiveDataFromForm1 before you actually have showed the form, therefor it probably isn't going to return anything. Also, you don't need the hide the existing form when calling ShowDialog as it will stay on top until you close it.
Your code is a real mess so I'll just throw something together as an example to help you progress;
In Program.cs:
frmReservations reservations = new frmReservations();
if (reservations.ShowDialog() == DialogResult.OK)
{
string result = reservations.yourDesiredResult;
Application.Run(new frmMain(result));
}
else
{
Application.Exit();
}
Now, inside frmReservations:
public partial class frmReservations : Form
{
public string yourDesiredResult = string.Empty;
private void btnClose_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.yourDesiredResult = "I've been set!";
this.Close();
}
}
Now inside frmMain you will have to receive that value again we've received from frmReservations and set in Program.cs:
public partial class frmMain : Form
{
public frmMain(string resultFromReservations)
{
InitializeComponent();
//resultFromReservations holds the string: I've been set
}
}
This is just an example to show you one of the many ways to do this, you will now have to implement it inside your program.
I found my bug. It was in Program.cs :
I had :
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 myStart = new Form1();
Form2Reservations myLogin = new Form2Reservations();
if (myStart.ShowDialog() == DialogResult.OK)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(myLogin);
}
else
{
Application.Exit(); // here was the mistake
}
}
All I had to do is to change Application.Exit(); to Application.Run(myStart);
, but I also needed to include this line in my second form button that closes the second form :
this.DialogResult = System.Windows.Forms.DialogResult.OK;
Thank you guys for help. I could not have fixed it without your help.

show same form which was hidden before

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...

Switching to hide and show between Windows Forms?

I have 2 forms Form1 and form2.First time Form2 is being load by below code and this is my sign in page..
application.run(new form2())
But after sign in i want to load another form Form1.How will i load it.If i am creating new From2() this is making new form not showing respected controls there.
I'd do something like this inside Form2 (or wherever you check the login data)
private void btnLogIn_OnClick(...)
{
if(/* perform credential test here */)
{
(new Form1()).Show(); // create and show the other form
this.Close(); // close this form
}
else
MessageBox.Show("Login invalid!");
}
How about this?
Form2 form = new Form2();
form.Show();
Try the following...
Form2.Show();

Categories

Resources