Passing a value back to original form
I have two forms: Form1 and Form2. I can get the contents of a List in Form1 to another开发者_Python百科 List in Form2 by calling a new Form2 and passing the values in. I update the List in form2 by say, removing an item from it. How would I pass the contents of Form2's list BACK to the original List in Form1? Form1 is the first form that appears when the application runs, so I don't want to call a new instance of the form.
You can pass the initial instance of Form1
to Form2
and use this reference to pass data back to Form1
.
// A property `Form2`
public Form1 RefToForm1 { get; set; }
// On form 1, after initializing `Form2`:
Form2 frm2 = new Form2();
frm2.RefToForm1 = this;
Note:
There are better solution than the above (it is quick and dirty). A better option would be to create a property on Form2
with the type of data you need in Form1
and access the data through it:
// A property `Form2`
public List<int> Form2DataForForm1 { get; set; }
// On form 1
var dataFromForm2 = frm2.Form2DataForForm1;
I suggest you implement a property in Form2 that returns the relevant data, and have Form1 read that property, "pulling" the data from Form2.
This is better than having Form2 "push" the data back into Form1, since it keeps the dependencies one way only.
精彩评论