Home >Backend Development >C++ >How to Pass Variables Between Windows Forms Using Delegates and Events or Constructors?

How to Pass Variables Between Windows Forms Using Delegates and Events or Constructors?

Barbara Streisand
Barbara StreisandOriginal
2025-01-03 21:34:39174browse

How to Pass Variables Between Windows Forms Using Delegates and Events or Constructors?

Passing Variables between Windows Forms Forms using Delegates and Events

In this scenario, where you have a main form and a "settings" child form, a common approach to pass a variable to the child form is through the use of delegates and events.

Step 1: Initialize a Delegate and Event

In your main form, create a delegate and event to handle the data transfer:

public partial class MainForm : Form
{
    /// <summary>
    /// Delegate to send data between forms
    /// </summary>
    public delegate void PageInfoHandler(object sender, PageInfoEventArgs e);

    /// <summary>
    /// Event of the delegate
    /// </summary>
    public event PageInfoHandler PageInfoRetrieved;
}

Step 2: Pass the Variable in the Event Handler

When you click the "Settings" button on the main form, create an event argument instance with the variable you want to pass and raise the event:

private void toolStripBtnSettings_Click(object sender, EventArgs e)
{
    PageInfoEventArgs args = new PageInfoEventArgs(SomeString);
    this.OnPageInfoRetrieved(args);

    SettingsForm settingsForm = new SettingsForm();
    settingsForm.ShowDialog();
}

Step 3: Retrieve the Variable in the Child Form

In your "settings" form, handle the event by overriding the corresponding event handler:

public partial class SettingsForm : Form
{
    protected override void OnShown(EventArgs e)
    {
        base.OnShown(e);

        // Retrieve the event arguments
        PageInfoEventArgs args = this.Tag as PageInfoEventArgs;
        if (args != null)
        {
            // Access the passed variable
            string receivedText = args.PageInfo;
        }
    }
}

Using a Constructor to Pass Variables

Alternatively, you can also pass the variable directly to the constructor of the child form:

public partial class SettingsForm : Form
{
    private string receivedText;

    public SettingsForm(string text)
    {
        this.receivedText = text;
    }
}

In this case, you would create the child form instance with the variable as an argument:

SettingsForm settingsForm = new SettingsForm(SomeString);

The above is the detailed content of How to Pass Variables Between Windows Forms Using Delegates and Events or Constructors?. 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