Switching between forms - c#

Anytime I want to display a new form, I create a new form object and hide the current form.
For example:
this.Hide();
new Form2().Show();
In this way, a new object keeps getting created over and over, and the old form is still running but hidden somewhere.
I would like to know what would be the most appropriate way to do so, I've been doing this for long time and anytime I do this I feel like I am doing it wrong. I mean how can we access the previous object and set it back to show instead of creating a new one.

Use Application.OpenForms property to get already opened form object and show that.
The OpenForms property represents a read-only collection of forms
owned by the application. This collection can be searched by index
position or by the Name of the Form.
Form1 frm1 = Application.OpenForms["Form1"] as Form1 ;
if (frm1 != null)
{
frm1.Show();
}

Related

MenuStrip not updating when editing it from another form (C#)

I've been having an issue that's been bugging me for the past 3-4 hours.
Basically, I have a main form, that is an MDI parent. I have another form, that is an MDI child of that parent. I use the second form for logging in and after I've been logged in, I want to add new items to the menuStrip of that main form, but for some reason I can't. I tried debugging and I saw that the menuStrip's indexes are expanding correctly for the new items, but they are not being updated in the form. I tried displaying the main form again with this.Show. This worked! I got a new form displaying the new items in the menuStrip. However, I just want to update them and not create another form. I tried refreshing/updating, but nothing worked. :/ Any suggestions?
Thank you!
EDIT:
Here is some more info:
this is the code from the 2nd form
if (successLogin==DialogResult.OK || successLogin==DialogResult.Cancel)
{
Form1 main = new Form1(); //define main form
FullUser = textBox1.Text; //getting the username (will use it for the menuStrip items "Logged in as: "+ FullUser)
main.LogedIn(FullUser);//calls method
this.Close(); //closing the 2nd form
}
that calls for the public method in the main form
public void LogedIn(string user)
{
menuStrip1.Items.Add("Item here"); //adding the item to the menuStrip
}
Edit 2: I put a timer which starts when opening the 2nd form and checks for a public boolean. That got it working, but still not the way I wanted it to.
You are creating a new form of type Form1 in the line:
Form1 main = new Form1();
And adding the items to that new form, instead of your existing one.
If the form is the MDIParent of the second form as you state in your question, you could change that line to:
Form1 main = (Form1)this.MDIParent;
If it's not, then you need to keep a reference to the existing form. If you create a new one (like you are doing) then the items are added to that new one, but not to the one that is already created.

Getting listbox items to display to another form

I'm still new here so please consider. My question is that I have two forms, (form1 and form2). In form1 there's a listbox with customers names on it. Now what i want is when the user clicks a name on the listbox, a new form (form2) pops up and displays the rest of the information of the customer (age,address,phone number) on the textboxes. When I click a name on the listbox it displays the rest of the info but only on that form, I can't get it to display on another form. I'm coding it using Visual studio, C#. Any help would be appreciated. Thanks!
You have to pass information from form1 to form2 in one way or another.
If the data for customers is collected within a class, you can simply pass the object that corresponds to the selected index in the listbox.
For instance if your customer data in form1 is set up like this:
List<CustomerData> Customers { get; set; }
And each object in that list corresponds to its respective index in the listbox, then you would need a form2 constructor similar to this:
public form2(CustomerData customer){
// set all form data here based on the customer
}
Potentially, if you asign the passed object in form2, you can manipulate the object within form2 and it will automatically update in form1 as well (assuming it is a class).
Then create your listbox click event method and open the form, passing the selected customer:
if(listbox.SelectedIndex < 0) return;
form2 f = new form2(Customers[listbox.SelectedIndex]);
f.Show();
I hope this is what you were looking for. A bit difficult to understand from your original question.

How to hide a form from a panel in another class?

I want to hide a form in panel1(form content) using this code:
frmChangePassword frmChangePassword = new frmChangePassword();
frmChangePassword.Hide();
with no luck. Here is my code to display in a panel:
//SHOW CHANGEPASSWORD FORM
if (isChangePasswordActive == false)
{
isChangePasswordActive = true;
frmChangePassword frmChangePassword = new frmChangePassword();
frmChangePassword.TopLevel = false;
frmChangePassword.Parent = this.panel1;
frmChangePassword.Show();
}
Is there a way to clear the content in my panel and display a new form in the same panel?
Many thanks in advance.
You are creating a new instance of the Password form. You need to get the current instance and then hide it. There are two ways I can think of:
Retain the frmChangePassword object you have created to show the form and call hide method on that object. You may have to change the scope of that object.
Use Application.OpenForms collection to get the opened instance of password form and hide it.
I would go with first approach.
Well, the problem is that you're creating a new form and then hiding the panel on that form. You can tell because you used the new keyword:
frmChangePassword frmChangePassword = new frmChangePassword();
frmChangePassword.Hide(); // affects the ^^ NEW instance ^^ you just created!!
So the code actually works fine in that it does exactly what it's supposed to be doing, it just doesn't produce the result you intended, which was to hide the panel on the existing instance of the form.
That gets a little bit tricker, because you have to find a way to get a reference to the existing instance of the form. In order to tell you how to redesign your code to do that, I'd have to see more of the code. Generally, the method you're writing this code in (the one that needs to do the hiding) will take a parameter of type Form (or even frmChangePassword), and the caller will pass in the current instance of the form to be modified.
If you still need it.
You have to declare a global varible of type Form in your public class:
Form frm = new Form();
Every time you trigger a new form load be sure to put first: frm.Hide();
and then intitialize the variable with the new form that will show:
frm.Hide();
frm = new thenewForm() { Dock = DockStyle.Fill, TopLevel = false, TopMost = true };
this.yourPanel.Controls.Add(frm);
frm.Show();
The properties I put in the "{" might change depending on the style you want, but if you want to have it as a borderless window you can copy those.

Windows Form Launching Another Form

I am quite new to Visual Studio (Express) and C#. I have made a windows form that accepts some user input then displays that input in a Message Box (that automatically comes with an "OK" button that closes the Message Box when clicked).
Instead I would like the user input collected by the first form to be displayed in a new form that displays a message (label), shows the input, and offers a choice of two buttons: one to accept and one to go back and change the input.
I have NO idea how to do this and any advice is appreciated.
Sounds like you need a confirm Message or something similar.
The MessageBox class offers this functionality.
DialogResult btn = MessageBox.Show("your message",
"your title",
MessageBoxButtons.OKCancel,
MessageBoxIcons.Question);
if(btn == DialogResult.Cancel)
// User canceled, return to the string editor
else
// User confirmed, do you work
If you prefer there is also an enum for MessageBoxButtons.YesNo with corresponding DialogResult.Yes and DialogResult.No
See here for a reference on MessageBoxButtons
See here for a reference on MessageBoxIcons
What you need is to somehow pass the information from the first form to the second. This can be done by setting properties on the child form, either through individual properties (strings, ints, etc.) or by a complete data structure (object). The input form collects the information, creates the sub child form, sets properties on it, then displays the form. Many other ways to do this, but start with the simple and then build up to the complex.
If you need to pass some data to your second form, create property/properties on that form, or provide data via constructor parameters. Also assign DialogResult property for two buttons on second form. Set DialogResult.OK to button which will accept input. Verify value returned by second form, when you show it as dialog and do appropriate actions:
using(SecondForm secondForm = new SecondForm()
{
secondForm.Data = yourData;
if (secondForm.ShowDialog() != DialogResult.OK)
{
// go back and change input
return
}
// accept input
}
So your Form2 needs to have some value, provided by whatever creates it, for it to exist. There should never be an instance of Form2 without that information. That tells you that it should be in that form's constructor (as opposed to a property on that form).
This means that in Form1 you will have something like this:
string someData; //populate based off of user input
Form2 childForm = new Form2(someData);
//then hide current form and show child form
In Form2 you probably already have a constructor, you just need to modify it to something like:
public Form2(string someData) //TODO give better parameter name
{
someLabel.Text = someData;
}
Next we need to deal with the child form going back to the parent form. I feel the preferable way to deal with this is using events. The form has a FormClosing event that you can attach to; this will allow your parent form to run some code when the child form is closed.
string someData; //populate based off of user input
Form2 childForm = new Form2(someData);
childForm.FormClosing += (sendingForm, args) =>
{
this.Show();
bool result = childForm.DidUserAccept;
}
Here I used a property on the child form DidUserAccept, for whether the user accepted or declined the value. We'll need to define that in Form2:
public bool DidUserAccept {get; private set;}
In the button click handlers for accept/cancel you can set the result accordingly and then close the form (closing will trigger the closed event and runt he relevant code in Form1.

How to pass a value selected on an initial form to the main form?

I want to do something like the answer here:
How can I close a login form and show the main form without my application closing?
...but I want to pass a value selected on the initial form to the next (main) form. If I call an overridden constructor on the main form, where do I store the value in the meantime (between the initial form being dismissed and the main form being called)?
OTOH, if, instead of using the program.cs file to do this, I create the "initial form" inside the main form's Load() event (is there a better place), I could do something like this, but admittedly it seems rather kludgy:
0) Set the main form's size to 0,0 to hide it
1) Show the "initial" form/modal dialog, and store the value the user selects (in a button click event) in a form-global variable
2) Once the initial form/modal dialog closes, set the main form's size back to what it should be (unless modal result <> OK, in which case I close the main form and the app)
I know there's a better way to do this...
You don't have to pass a value to the main form. Just like your link explains, open your main form first. Then your main form can open the other form. This other form can place the information in a public property that the main form can access. Since the main form controls the lifetime of this other form, the main form gets the information held in the other form's public property, then closes the other form.
string myVariable;
using (OtherForm otherForm = new OtherForm())
{
otherForm.ShowDialog();
myVariable = otherForm.OtherVariable;
}
Try using ApplicationContext (System.Windows.Forms.ApplicationContext). You can show multiple forms as shown in the example in the following MSDN thread. And regarding data,you can have a common data object which is created once and the forms are instantiated with the data object passed to them before showing them.
http://msdn.microsoft.com/en-us/library/system.windows.forms.applicationcontext%28v=vs.100%29.aspx

Categories

Resources