How to remember variable between two forms? [duplicate] - c#

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Referencing control on one form from another form VB.NET
This is the question following my last question. Its the last on today :D When i have two forms. One is main with whole aplication and the secondone is just for settings. I need set one variable in Form2 and then after close this form, need Form1 to get this variable from form2. What is the easiest way to transfer this variable?

Create a Property in Form2:
public MyType MyVariable { get; set; }
Set the Property in Form2 (for example, in the form's Close event)...
this.MyVariable = ...;
...and read the property in Form1:
...
myForm2Instance.ShowDialog(); // this is where you show Form2
var theValueFromForm2 = myForm2Instance.MyVariable;

The easiest (though not the best) way is to store the value in a public property on Form2 which can then be accessed from Form1.

You can pass the information into Form2 in the constructor and have a property on Form2 that exposes the information. Then when you are done with Form2, you can say myForm2.ThePropertyThatHasTheData inside of Form1.

Not the "easiest way"... but generally speaking, the MVC pattern is the current state-of-the-art for organizing the UI layer of an application. You get a clean separation of UI from the data that the UI is displaying, and from flow control in your application.
See for example https://stackoverflow.com/questions/2406/looking-for-a-mvc-sample-for-winforms

Your two forms are views. So, you just need a model class.
Create a class called Model or similiar
Create a public property called Setting or similiar
Instantiate the model from Form1
Model m = new Model();
Pass the Model to Form2 during the constructor or set private member.
Form2 f = new Form2();
f.Model= m;
f.ShowDialog();
Let's say the setting is a text box on form2. Before the form closes, set the setting:
Model.Setting = this.textBoxSetting.Text();
Since the Model is an object and passed by reference, the model object in form1 will automatically be updated since it is the object referenced.
If you want the data to be shared throughout your application, consider making the Model static or follow the singleton pattern if only 1 model is used per application.

Related

Assigning textbox value to a field in a separate form

I am sure this is an easy question to answer, but I am having difficulty implementing it how I need.
I am using Visual Studio 2013 and C#
I have two forms, one that loads when the app starts up which contains user-selectable settings such as user id, how many puzzle pieces that would like on screen... and a confirm button.
The second form is like a puzzle grid, which is generated when the user clicks the confirm button on the first form.
When the person has correctly solved the puzzle, a message box pops up with the time it took to solve.
What I want to be able to do is add the user id field into the messagebox string.
I have seen many examples of using event args and getting and setting fields but most are assuming one form is generated from a previous form, where I just want to 'grab' the information from one form and store it on the second form for use in a string.
Links to tutorials would also be appreciated if that is easier.
I found out what I was doing wrong, with the help of everyone's answers.
I had the variables declared on the first form, but they were declared in the textbox_leave and updownBox_leave methods when they should have been declared at the very top of the class.
Then I just called Form1.IdString and Form1.puzzleNumberString from my Form2 and what-do-you-know everything went as I thought it should.
It's pretty simple.All you need to do is pass your id variable to second form constructor.For example in your Confirm Button click:
Form2 f2 = new Form2(myVariable);
f2.Show();
And you should add a constructor to the Form2:
public string ID { get; set; }
public Form2(string id)
{
InitializeComponent();
ID = id;
}
Then you can use ID variable in your second form.
In your puzzle form create a global Form variable, then give the constructor a Form f parameter and set your global form variable as the passed parameter:
public Form form = null;
public PuzzleForm(Form f) //puzzle form constructor
{
form = f;
}
then go into your first form and where you create an instance of the puzzle form change it so that it passes an instance of this.
PuzzleForm pf = new PuzzleForm(this);
Now from inside your Puzzle form you can access your Form1 variables like so MessageBox.Show("UserID: "+form.userID.Text);

How can we call the controls from one form to another form of the same application

I have two forms in C# Window application as frm_Stock.cs and frm_Purchase.cs.
I want to use some controls of frm_Stock in the frm_Purchase.Is it possible?IF yes then how can i do this please give me suitable example.
Thanks in advance
You will have to pass a reference to the controls/form when constructing the other form, and use that reference. A rough example,
frm_Stock = new StockForm();
frm_Purchase = new PurchaseForm(frm_Stock);
then within the purchase form code...
public class PurchaseForm : Form
{
public PurchaseForm(StockForm frm_Stock)
{
frm_Stock.SomeControl.Text = "blah";
}
}
It is possible but not recommended way of doing it, you should have pass it to the other form via some shared object(i-e StateBag ). You can make the controls of Frm_Stock public and then they will be accsible from frm _Purchase when you make frm_Stock instance.
You should create a custom user control and use it on both forms.
If you want to share the same instance of the user control across the form, then create an instance when your application starts and add it manually on both forms when they load.

Accessing the parent Form

I know that the title might seem silly, couldn't think of something better, sorry.
I have 2 Forms (C#), the main-form holds an instance of the second.
Is there a way to.. get access to the running instance of Form1 (The entry point) and to his properties from the instance of form2?
Everybody tells me to learn OOP.
I did, a long long time ago, and I still don"t get it.
When the main form instantiates the second form, it could pass a reference to itself to the constructor of the second form.
Thus, the second form will have access to the public members of the first.
EDIT
In the Form1 you instantiate Form2 somewhere and pass it a reference to Form1 in ctor:
Form2 f2 = new Form2(this);
In the class definition of Form2 add a field:
private Form1 m_form = null;
In the constructor of the second form set that field:
public Form2(Form1 f)
{
m_form = f;
}
Then, everywhere in your Form2 you have access to Form1 through the means of m_form
You probably instanciated Form2 from within Form1. After instanciating and BEFORE showing it you could set a property on Form2 that refers to Form1 like this:
Form2 f2 = new Form2();
f2.TheParent = this;
f2.Show();
Of course you have to add the TheParent property to the Form2 class to be able to do that.
Warning: although it is possible this way a better solution might be to create a seperate object that holds all required/shared data andd pass that object to each form in a similar way. This will prevent your code from becoming too coupled.
One approach to this can be creating an owner-owned relationship.
// Create a form and make this form its owner
Form ownedForm = new Form();
ownedForm.Owner = this;
ownedForm.Show();
or as a shortcut, you could pass the owner form as an argument to an overload of the Show method, which also takes an IWin32Window parameter
ownedForm.Show(this); // established owner-owned relationship
Then you could access the main form properties like this
((MainForm)this.Owner).ownerVariable;
In order for this variable/method to be accessible, it has to have the internal protection modifier.

What is best way to pass variables between GUI in Winforms C#?

I've WinForms program with 2 GUI's. I work with one GUI and open another GUI using
var gui = new FormGui("SomeVar", someOthervar);
gui.ShowDialog();
I use ShowDialog() or Show() depending on what I need to get. When I'm done I would like to pass results (sometimes it's 2 strings, sometimes it's more then that) back to the Mother GUI which called Child GUI.
What's the best way to do that? I was thinking about using global variables but not sure if that's best approach?
You can create properties on your FormGui and set those within the form. When you're done with the form, you can grab those properties from your reference to the form:
var gui = new FormGui("SomeVar", someOthervar);
gui.ShowDialog();
var result = gui.Result;
EDIT: Regarding your comment:
Say your child form has some button on it or something that the user can interact with. Or if there's a close button they click on:
private void buttonCloseClick(object sender, EventArgs e)
{
this.Result = new ResultObject()....
}
EDIT #2 Regarding your second comment:
Yes, on your FormGui class, you need to define an object called Result:
public partial class FormGui : Form
{
public ResultObject Result {get;set;}
}
ResultObject is just something I'm making up. The point being that you're in control of FormGui, so you can add any property you want, and then access it on the FormGui object.
You can add a property on the FormGui class that contains the results you want to use in the parent form.
Also, you can use the result of ShowDialog() to pass information back as well - although this is limited values of the DialogResult enum.
You can call with ShowDialog, on the child window, use a new public property to set the result, and when you close the dialog the parent GUI should be able to see the result in the next code line.
The answer by BFree is enough for your task
I am suggesting easy way to add properties to all forms
Make a new class extend it with System.Windows.Form
public class Form : System.Windows.Forms.Form
{
//add properties
}
Check your properties in your forms

How can I update a label on one form from another form in C#?

I want to update label of Form1 from Form2. So here's what I have:
// Form1
public string Label1
{
get { return this.label1.Text; }
set { this.label1.Text = value; }
}
// Form2
private void button1_Click(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
frm1.Label1 = this.textBox1.Text;
this.Close();
}
So the above code doesn't work. However, when I add the following:
frm1.Show();
after
this.Close();
in Form2 code, the Form1 obviously is being opened again (two windows). But I want it to update in the same window so I suggest this.Close() is unnecessary.
Anyone have any ideas?
In the button1_Click method, you're actually creating a new instance of Form1 and setting the Label1 property of that new instance. That explains why a second instance of Form1 is being shown on the screen when you add frm1.Show();. If you look at that second copy carefully, you'll see that it's label displays the correct value, but your original copy of that form retains its original value.
Instead, I assume that what you want to do is set the Label1 property for the existing instance of Form1 that is already displayed on the screen. In order to do that, you're going to have to get a reference to that existing form object.
Thus, this becomes a simple question of "how do I pass data between two objects (forms)", which has been asked countless times here on Stack Overflow. See the answers to these related questions:
Communicate between two windows forms in C#
Passing values between two windows forms
C# beginner help, How do I pass a value from a child back to the parent form?
Send values from one form to another form in c# winforms application
Try using singleton design pattern for that as I think the problem is when you using new
public class Form1Singleton {
private static final Form1Singleton INSTANCE = null;
// Private constructor prevents instantiation from other classes
private Form1Singleton () {
}
public static Form1Singleton getInstance()
{
if(INSTANCE ==null)
INSTANCE =new Form1Singleton();
return INSTANCE;
}
}
Now you can use the form easily only 1 form
private void button1_Click(object sender, EventArgs e)
{
Form1Singleton frm1 = Form1Singleton.getInstance();
frm1.Label1 = this.textBox1.Text;
this.Close();
}
I hope that solve your problem
BR,
Mohammed Thabet Zaky
Most probably: What you actually do is create a brand new instance of Form1 within the scope of Form2, while later in the control flow of your program another instance of Form1 is created and shown. Of course, in such a case you can't expect your label to be set correctly.
The best would be to decouple Form1 and Form2 from each other and instead pass only data along the control flow of your program.
When you say this.close that means all the values you set to that instance gets nullifies.
You can use delegate here, to set form values.
MVP pattern is good for this type of senario and also separate UI and business logic.
This thread is good reference:
UI Design Pattern for Windows Forms (like MVVM for WPF)

Categories