Reputation: 150
I have a form that I created that is supposed to load login information / settings that is seperate from the main form. I was wondering how exactly I would pass this information from one form to the other.
I figured you needed to use things like the form closed event (I was gonna pass the information as the form closed). But I am not exactly sure on how to go about it.
Upvotes: 1
Views: 1149
Reputation: 754575
There are two general approaches to doing this. The most straight forward one would be to add a new event to the helper form which is raised on completion of the login information being loaded. The main form can then listen to this event. Once it's recieved it can then close the helper form.
class LoginInformationEventArgs : EventArgs {
...
}
class HelperForm : Form {
...
public event EventHandler<LoginInformationEventArgs> LoginInformationLoaded;
...
}
class MainForm : Form {
LoginInformationEventArgs _loginInfo;
public void ShowHelper() {
var helper = new HelperForm();
helper.LoginInformationLoaded += delegate (sender, e) {
_loginInfo = e;
helper.Close();
};
helper.Show();
}
}
The second way is to use properties on the helper form. The form is responsible for setting them before it is closed and the main dialog can then read them directly off of the helper form once it's completed.
class LoginInformation {
...
}
class HelperForm : Form {
public LoginInformation { get; set; }
private void OnCompleted() {
LoginInformation = ...
this.Close();
}
}
class MainForm : Form {
public void ShowHelper() {
var helper = new HelperForm();
helper.ShowDialog(this);
Process(helper.LoginInformation);
}
}
Upvotes: 1
Reputation: 224867
No, you would use properties generally, or fields for a quick solution. In the form that obtains the information, return the data from properties:
public readonly int Age {
get {
return int.Parse(this.txtAge.Text);
}
}
for example. Then, you would access it like any other property, after the form has closed:
SomeForm someForm = new SomeForm();
someForm.ShowDialog();
int userAge = someForm.Age;
Upvotes: 2