1
Answer

sharing values between forms

Ralph

Ralph

19y
3.5k
1
I am a begining C# programmer using Visual Studio 2005 Beta and have the following question. 

How can I access values from common controls, like a ComboBox, or variables within Form1 (the parent) from Form2 (a dialog) and vice versa?

Scenario:
In Form 1 the User enters form data. 
In Form 2 the input data is processed and the results are displayed in a new form 
with readonly textboxes. 

An explanation plus a code snipplet would be apreciated.
Answers (1)
0
Nschan
NA 104 145.5k 19y
In windows programming, it is ok for a parent window to access a child/secondary window. But typically, having the child/secondary window access the parent directly is not a good idea. It creates a double dependency (class 1 depends on class 2 and class 2 depends on class 1) that makes it hard to reuse the child/secondary window in other situations.

Below is a simple example of a parent form that opens up a secondary results dialog:

class ParentForm
{
    ...
    private void showResults_Click(object sender, EventArgs e)
    {
        // 1. Create an instance of the results dialog.
        ResultsForm dlg = new ResultsForm();

        // 2. Copy necessary input data TO the results dialog.
        dlg.InputValue = Int32.Parse(this.inputValueTextBox.Text);

        // 3. Show the results dialog.
        if ( dlg.ShowDialog() == DialogResult.OK )
        {
            // 4. Optionally copy back any modified values FROM the results dialog.
            this.outputValueTextBox.Text = dlg.OutputValue.ToString();
        }
    }
}