Switching to hide and show between Windows Forms? - c#

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();

Related

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!

C# Switching forms with passed data in the constructor

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

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.

MDI Child Forms Opening each other with the same parent form

So I have 3 Forms, lets call them Form1, Form2, and Form3.
I have sent the IsMDIParent Property to true for Form1.
When I launch the app, It loads Form2 as an MDI Child using
Form2 frm = new Form2();
frm.MdiParent = this;
frm.Show();
And that works fine. What I then want to do is click a button withing the 2nd form that will close Form2 and open up Form3 as a child form of Form1.
I tried
SecondForm SecondFormMDI = new SecondForm();
SecondFormMDI.MdiParent = Form1;
SecondFormMDI.Show();
on the button click event in Form2, but it would not work.
Do I have to always launch a Child form from the parent form? and if so, how would i go about doing that when it is on the button click event on a child form?
Just use this.MdiParent, instead of Form1, like
SecondForm SecondFormMDI = new SecondForm();
SecondFormMDI.MdiParent = this.MdiParent;
SecondFormMDI.Show();
You can set the MDIParent of any form in design time, why do it in run-time?
Simply set the value of MDIParent property of Form2 and Form3 to Form1, and that's it.
You could create a method in your MDIForm to open a childform:
public void OpenForm(Form form)
{
form.MdiParent = this;
form.Show();
}
When you want to open a new form in another form you do something like this (example in ChildFormOne with button):
private void btnOpenChildFormTwo_Click(object sender, EventArgs e)
{
((MDIForm)this.MdiParent).OpenForm(new ChildFormTwo());
this.Close();
}
Hope this helps.
ChildForm frmChild = new ChildForm();
frmChild.MdiParent = this.MdiParent;
frmChild.Dock = DockStyle.Fill();
frmChild.Show();

Close child form if already open

How can I go about closing a Child form if it's already open? And if it isn't already open, then open it?
Thank you
I already have this code, which doesn't work, obviously:
Form ibx = new inbox();
if(ibx.Visible)
ibx.Dispose();
else
ibx.Show();
All that the above does is creates a new form whether or not it's already open.
private Form frm;
public void ToggleForm() {
if(frm == null) {
frm = new Form();
frm.Show();
}
else {
frm.Close();
frm = null;
}
}
If what you want to achieve is opening a form only if it isn't already open, then bring it on front when it is, then the following code might help.
private void tsmiMenuOption_Click(object sender, EventArgs e) {
// Assuming this method is part of an MDI form.
foreach(Form child in this.MdiChildren)
if (child.Name == MyForm.Name) {
child.BringToFront();
return;
}
MyForm f = new MyForm();
f.MdiParent = this;
f.Show();
}
So, this is untested pseudo-c#-code that verifies if MyForm is already opened and contained in the MdiContainer.Children. If it is, then it brings this form (MyForm) to the front. If it is not, then it simply instantiate and opens it.
Is this about what you want?
In your main form, when you create the first childform, keep a reference to it. Currently you're creating a new childform every time you run that code and then you check if the newly created form is visible.
Also be aware that your subject talk about opening and closing but your code seems to just be dealing with hiding and showing.
Carra's code is a good sample how to do it, but be careful if the childform can be closed from anywhere else.
You need to keep a reference to ibx. Your code creates a new inbox everytime it's run.
Module Module1
Public Function InstanceNewForm(ByRef ParentForm As Form, ByRef Childform As Form) As Boolean
Dim bOpen As Boolean = False
Dim frm As Form
For Each frm In ParentForm.MdiChildren
If Childform.Name = frm.Name Then
Childform.Focus()
bOpen = True
Exit For
End If
Next
If Not bOpen Then
With Childform
.StartPosition = FormStartPosition.CenterScreen
.MdiParent = Parentform
.Show()
End With
End If
frm = Nothing
Return bOpen
End Function
End Module
The above code will check to see if a mdi form is already loaded in the parent container and if its already active will set the focus to it. Otherwise it will create the mdi form.
Just call it from anywhere the mdi form needs to be loaded. ex: call InstanceNewForm(me,form2)
Works like a charm everytime!!

Categories

Resources