Home > Backend Development > C++ > How Can I Pass a Variable Between Forms in Windows Forms Applications?

How Can I Pass a Variable Between Forms in Windows Forms Applications?

Patricia Arquette
Release: 2025-01-01 10:28:11
Original
244 people have browsed it

How Can I Pass a Variable Between Forms in Windows Forms Applications?

Passing a Variable Between Forms in Windows Forms

In Windows Forms applications, passing data between forms can be achieved using delegates and events. The problem arises when one form, the "child" form, requires accessing a variable from the "parent" form.

To solve this, consider utilizing delegates to send data from the parent form to the child form. In the parent form, define a delegate and an event handler for it. When the button to open the child form is clicked, create an event argument object carrying the variable value and raise the event.

In the child form, subscribe to the event in the constructor. When the event occurs, retrieve the variable value from the event argument object. Modify the child form's controls or properties to display the variable text dynamically.

Here's an example code in C#:

// Parent Form
public partial class MainForm : Form
{
    public delegate void PageInfoHandler(object sender, PageInfoEventArgs e);
    public event PageInfoHandler PageInfoRetrieved;

    private void toolStripBtnSettings_Click(object sender, EventArgs e)
    {
        PageInfoEventArgs args = new PageInfoEventArgs(SomeString);
        OnPageInfoRetrieved(args);
        SettingsForm settingsForm = new SettingsForm();
        settingsForm.ShowDialog();
    }

    private void OnPageInfoRetrieved(PageInfoEventArgs args)
    {
        if (PageInfoRetrieved != null)
            PageInfoRetrieved(this, args);
    }
}

// Child Form
public partial class SettingsForm : Form
{
    private string m_Data; // Variable to store the passed value

    public SettingsForm()
    {
        InitializeComponent();
        Subscribe to PageInfoRetrieved event
    }

    private void OnPageInfoRetrieved(object sender, PageInfoEventArgs e)
    {
        m_Data = e.Value;
        // Update controls or properties in this form
    }

    public string Data => m_Data; // Expose the variable as a property
}
Copy after login

The above is the detailed content of How Can I Pass a Variable Between Forms in Windows Forms Applications?. 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