Home >Backend Development >C++ >How to Modify Controls in One Windows Form Based on Another Form's Selection?

How to Modify Controls in One Windows Form Based on Another Form's Selection?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-31 07:26:10270browse

How to Modify Controls in One Windows Form Based on Another Form's Selection?

Data interaction between windows: Modify the control value according to the selection of another window

How to change the control value in a window based on the choice of another window? For example, when the combination box in Form 1 needs to fill the data according to the lines selected in the data grid in Form 2, this problem will occur.

Solution:

In C#, the data communication between the windows is similar to the interaction between the class. Here are several methods to achieve this goal:

Operation FORM 2 in Form 1:

Set parameters in the constructor of Form 2: Create an instance of Form 2 and pass the required value as the parameter.

Create public attributes or methods in Form 2: configure the required attributes or methods in Form 2, and visit them from Form 1.
  • Public the Form 2 control to the public: allow Form 1 to directly access specific controls in Form 2.
  • Operation Form 1 in Form 2:

Pass the instance of Form 1 to Form 2: Create a attribute or method that can access from Form 2 in Form 1. Event from Form 1 Subscribe to Form 2: Create an event in Form 2 and subscribe to it from Form 1.

    Define an Action property in Form 2: When creating an instance of Form 2, a operation is assigned to this attribute to trigger the required behavior in Form 1.
  • Public Form 1 control to the public: pass the instance of Form 1 to Form 2, and directly modify the public control.
  • Code example:
  • Operation FORM 2 in Form 1:

Use the constructor method:

In Form 1:

Operation Form 1 in Form 2:

<code class="language-csharp">public partial class Form2 : Form
{
    int selectedValue;
    public Form2(int value)
    {
        InitializeComponent();
        selectedValue = value;
    }
    //...
}</code>
Use ACTION attribute:

<code class="language-csharp">int value = 2;
var f = new Form2(value);</code>
In Form 1:

By using these technologies, you can effectively realize interaction between different windows in Windows Forms applications.

The above is the detailed content of How to Modify Controls in One Windows Form Based on Another Form's Selection?. 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