how to open a form from another form in c# - 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!

Related

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.

Going from 2nd form back to the first form in the same instance

I have a program that consists of two winforms and three classes, one of which is static. My first form does some work and has a button that opens the second form. When the second form opens, the first one closes via this.Visible = false.
I have a button on the second form that I want to take me back to same instance of the first form so that I can input more information if needed. Any new information would have to be added to the original information so that I can go back to the second form.
Is there a way to do this? I tried instantiating a new form but of course the previous values were gone.
Here is the code for my first form to open the second:
//event handler to call Daily Summary form
private void btnDailySummary_Click(object sender, EventArgs e)
{
DailySummaryForm form2 = new DailySummaryForm();
this.Visible = false;
form2.Show();
}
Here is the code for my second form to reopen the first:
private void btnRtnToOrderMenu_Click(object sender, EventArgs e)
{
//closes Daily Summary form
this.Close();
}
I tried doing "OrderForm.Visibile = true" but of course without instantiating a new instance that doesn't work. I'm at a loss.
When you create Form2, you can pass in a reference to Form1 in the constructor.
So Form2 constructor:
public Form2(Form form1)
{
//Do stuff with form1, such as store reference to use later
}
And then when you create Form2 in Form1, you can do this:
Form2 form2 = new Form2(this);
There are a lot of ways, but here is one that I like the design of:
private void btnDailySummary_Click(object sender, EventArgs e)
{
DailySummaryForm form2 = new DailySummaryForm();
this.Visible = false;
form2.Show();
form2.Closing += (sender, args) =>
{
this.Show();
}
}
(Note: this is all offhand; may need minor syntactical fixes to compile).
This way form2 doesn't need to know about form1 at all, it just knows that someone else wants to run some code when it gets closed. Form1 on the other hand is able to tell form2, open me when you're done. The most common/trivial example is to just pass the instance of Form1 around (as another answerer has already proposed) but this exposes everything about Form1 to Form2, allowing it to do a lot of things that you might not want. It also increases the coupling between the two forms (meaning you can't use one without the other).
Does Form2 need to keep the old information when you go back to form1? If so, then you need to make sure that, when you reopen Form2, you are not creating a new object.
DailySummaryForm form2;
private void btnDailySummary_Click(object sender, EventArgs e)
{
if(form2 == null) //Check for null ...
form2 = new DailySummaryForm(); //..and create new Form2 if it is null.
this.Visible = false;
form2.Show();
}
This way, when you re-open Form2 after the first time, the old information will still be there and then you could simply add the new information.
At this point, it'd be best to create some sort of event in Form1 that, when raised, causes something (such as an update) to happen in Form2.
Otherwise, if you do not need to keep the old information, feel free to dispose of Form2 when you switch back to Form1 and simply pass the new version of the information from Form1 into Form2 using a constructor like others have suggested.

How do I set the caption of one form when another form closes (C#)

I'm working on an application and I've encountered a strange issue, that I think should be simple, but isn't. What I'm trying to accomplish is set the main form's title caption to a specific value when the another form closes. Below is my most recent attempt at this.
// From the main form I have
ObjectForm Objects = new ObjectForm();
Objects.GameName = this.Text; // this is a public string on the ObjectForm side
// Here is what I have on the ObjectForm
private void btnOK_click(object sender, EventArgs e)
{
MainForm Main = new MainForm();
Main.Text = this.txtGameName.Text;
this.Close();
}
Any help will be gladly accepted, thanks :D
You can't just instantiate a new MainForm, you need to get a reference to the existing instance.
Have a look in the documentation at Application.OpenForms
This code you have in your button click handler
MainForm Main = new MainForm();
Main.Text = this.txtGameName.Text;
Instantiates a new MainForm and sets it's title, this is completely separate instance to the MainForm that houses your application.

public DialogResult ShowDialog() help!

I have two forms.
The first form is the mainForm, this never goes anywhere.
On opening the second form (saveForm), it will display over the top.
When i close this form, I want a certain piece of code in the mainForm to run.
I assume this is the correct way to get this to happen?
The code on saveForm when I close and return to the mainForm:
private void btnSaveDetails_Click(object sender, EventArgs e)
{
Delivery d = new Delivery(txtNameBox.Text, txtAddressBox.Text, txtDayBox.Text, txtTimeBox.Text, txtMealBox.Text, txtInstructionsBox.Text, txtStatusBox.Text);
mainForm.myDeliveries.Add(d);
this.Close();
}
Any ideas?
You can use the DialogResult returned to effect some change in your application. For example, if you provided the user with a dialog asking whether or not they want to delete all files and they respond by clicking the Yes button on your dialog, you would then delete the files.
More information about how to use DialogResult and ShowDialog vcan be found here: DialogResult
UPDATE: If the code you posted is from your "child" form, then what you've done so far is probably fine, BUT, you still need to provide a DialogResult on that form to communicate to mainForm that something was done. For example, you could do the following before this.Close():
this.DialogResult = DialogResult.OK;
Then, in the code after the call to childForm.ShowDialog(), check the DialogResult. If it's equal to DialogResult.OK, then you can perform whatever task you need to that indicates the user clicked OK.
(And, on a side note, Dispose() is not called when you use ShowDialog(); you'll need to clean things up yourself, if necessary.)
You have to set the DialogResult property of you dialog form. Either explicitly in code or by assingning the dialog result to a button on your form.
private void btnSaveDetails_Click(object sender, EventArgs e)
{
Delivery d = new Delivery(
txtNameBox.Text, txtAddressBox.Text, txtDayBox.Text,
txtTimeBox.Text, txtMealBox.Text, txtInstructionsBox.Text,
txtStatusBox.Text
);
mainForm.myDeliveries.Add(d);
this.DialogResult = DialogResults.OK;
}
No need to call Close() setting this.DialogResult does that for you if you called the dialog using ShowDialog().
On calling the form you have to do the following:
var frm = new MyForm();
if (frm.ShowDialog() == DialogResults.OK) {
// do what you want to do on success.
}

Categories

Resources