Home >Backend Development >C++ >How to Effectively Transfer Data Between C# Forms?

How to Effectively Transfer Data Between C# Forms?

Susan Sarandon
Susan SarandonOriginal
2025-01-31 23:56:09896browse

How to Effectively Transfer Data Between C# Forms?

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>
Step 2: Form1 -Get the value of the submitted

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>
In Form2, create a public attribute as the source of the submit value:

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:

    In Ferm2, the text of TheVALUE attribute returns the text in the text box named Textbox1:
<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>
By following these steps, you can easily pass data between the windows to achieve efficient communication and interaction in the application.

    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!

    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn