Data transmission between the windows: complete guide
When building a dynamic interactive application, the value of the windows is transmitted to it. This guide will introduce an effective method, and use C#to pass data between two windows (Form1 and Form2).
Step 1: Form1 -Open Form2
In the Form1 button click the event, use the following syntax to initialize the new instance of Form2:
ShowDialog () method display Form2 with a modal dialog box. Form1 will not be accessible before Form2 is closed.
<code class="language-csharp">using(Form2 form2 = new Form2()) { // 以模态对话框方式打开Form2 form2.ShowDialog(); }</code>
FORM2 is closed, check the results of the showdialog () call. If the dialogresult is OK, the value of the submitted from Form2:
Step 3: FORM2 -Provide public attributes for value exchange
<code class="language-csharp">if(form2.ShowDialog() == DialogResult.OK) { someControlOnForm1.Text = form2.TheValue; }</code>
This attribute retrieves the text in the Form2 text box, allowing Form1 to access it.
Example implementation
<code class="language-csharp">public string TheValue { get { return someTextBoxOnForm2.Text; } }</code>
Consider the following simplified example:
In Form1, the button click the event to open Form2 and give the submitted value to the label:
<code class="language-csharp">private void Button1_Click(object sender, EventArgs e) { using(Form2 form2 = new Form2()) { if(form2.ShowDialog() == DialogResult.OK) { label1.Text = form2.TheValue; } } }</code>
The above is the detailed content of How to Effectively Transfer Data Between C# Forms?. For more information, please follow other related articles on the PHP Chinese website!