Home >Backend Development >C++ >How to Efficiently Pass Values Between C# Forms?

How to Efficiently Pass Values Between C# Forms?

Susan Sarandon
Susan SarandonOriginal
2025-01-31 23:36:09360browse

How to Efficiently Pass Values Between C# Forms?

C#window value transmission: practical method

In the C#application with multiple user interfaces, the value transmission between the windows achieve seamless data exchange. This article will guide you how to pass the value between the two windows through a simple example, and solve the problem of the visibility and data access of the form.

Problem background:

You have two windows, form1 and form2. Form1 contains a button to open Form2 to turn Form1 into a non -active state. Form2 contains a text box and a submission button. When the user enters the message in the text box of Form2 and clicks the submission button, Form2 should be closed, and Form1 should become a activity state and display the submitted value.

Implementation plan:

To achieve this function, please follow the following steps: Open Form2 from Form1:

In this code, the ShowDialog () method opens Form2 in a modular window and disable Form1 until it is closed. If the user clicks the submission button in Form2, it will return Dialogresult.ok and continue to execute the code in the IF statement. Value of access Form2:

<code class="language-csharp">// Form1按钮点击事件中的代码
using (Form2 form2 = new Form2())
{
    if (form2.ShowDialog() == DialogResult.OK)
    {
        // 使用Form2返回的值执行操作
    }
}</code>

Create a public attribute called a transmitted value in Form2 to disclose the value of the text box. This allows FORM1 to access the message.

Turn off FORM2 and refresh Form1:

<code class="language-csharp">// Form2中的代码
// 公共属性,用于返回文本框的值
public string 传递的值
{
    get { return someTextBoxOnForm2.Text; }
}</code>
When the user clicks the submission button in Form2, close the window and update the value in Form1:

This will close Form2 and return the control to Form1. In the IF statement in the Form1 button, retrieve the values ​​and attributes passed from Form2 and display it appropriately. By following these steps, you can effectively pass the value between the C#windows to achieve communication and data exchange between different user interfaces in the application.

The above is the detailed content of How to Efficiently Pass Values 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