开发者

How to remember variable between two forms? [duplicate]

This question already has answers here: 开发者_Python百科 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜