There are many ways to pass data between form in .NET. This article, Passing Data Between Forms, at the Code Project is an excellent one that shows 4 ways to do it. My favorite way to do it is with delegates and events.
However, very often you simply need a quick and dirty solution where you open up a quick data entry form and get the data back. Using delegates and events is overkill.
Well, I needed to do it yet once again for some software for Super Simple, and while looking at some past code of mine, I thought, “Wow! Man, that’s sneaky!” So, here I’ll explain a quick and dirty little way to get some fast data with minimal coding and almost zero effort.
The basic method is to:
- Open a new form
- The user enters the data and closes the form
- In the OnClosing event, save the data to Properties.Settings.Default.SomeVariable
- In the main form, get the data back from the settings
So, in code, that looks like this:
In Form1 (the main form):
Form2 form2 = new Form2(); form2.ShowDialog(); string myVariable = Settings.Default.SomeVariable;
In Form2 (the data entry form):
private void btnOk_Click(object sender, EventArgs e) { Properties.Settings.Default.SomeVariable = txtSomeVariable.Text.Trim(); this.Close(); }
Quick, easy and just a little bit sneaky~!