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

How to Pass Values Between Forms in C#?

Mary-Kate Olsen
Release: 2025-01-31 23:41:10
Original
280 people have browsed it

How to Pass Values Between Forms in C#?

When using multiple windows in the C# application, you usually need to pass the value between the windows. This article will gradually explain how to achieve this goal.

In order to pass the value between Form1 and Form2, we will use the following methods:

    Create a public attribute in Form2 to openly open the value that needs to be passed.
  1. Show Form2 in a modular manner to ensure that Form1 keeps non -activity.
  2. retrieved the value from the attributes of Form2 and assign it to the control in Form1.
  3. The following is a simple example:
  4. In this example:

Display FORM2 in a modular manner to ensure that Form1 keeps non -activity status.

<code class="language-csharp">// Form 1
// 在按钮点击事件中
using(Form2 form2 = new Form2()) 
{
    if(form2.ShowDialog() == DialogResult.OK) 
    {
        someControlOnForm1.Text = form2.TheValue;
    }
}</code>
Copy after login
If the user clicks the "OK" button on Form2, the
<code class="language-csharp">// Form 2
// 创建一个公共属性来提供值
public string TheValue 
{
    get { return someTextBoxOnForm2.Text; }
}</code>
Copy after login
method returns

.

    Then, we retrieve the value from the
  • attribute of Form2 and assign it to the control on Form1 (ShowDialog()).
  • ShowDialog() This method provides a simple and effect way to pass value in C#. Remember to reply DialogResult.OK and
  • with the actual names of you Ontrols. Consider More Robust Error Handling and Data Validation in Production Code.

The above is the detailed content of How to Pass Values Between Forms in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template