Passing Data Between Windows Forms
When managing multiple forms in a Windows Forms application, you may encounter situations where you need to share data between them. This article addresses the issue of passing a variable from a main form to a "settings" form, allowing the new form to display that information.
Using Delegates and Event Handlers
The code you provided in the main form uses delegates and event handlers to send data to the settings form. A delegate is a type that defines a signature for a method with specific input and output parameters. By assigning a delegate to an event handler, you can register methods to be invoked when the event occurs.
In this case, the main form creates a delegate PageInfoHandler with an input parameter of type PageInfoEventArgs. The PageInfoEventArgs class contains the data (in this case, a string) you want to pass to the settings form. When the "Settings" button is clicked, the event handler (OnPageInfoRetrieved) is invoked, which calls the registered methods (in this case, PageInfoRetrieved).
Retrieving Data in the Settings Form
In the settings form, you need to define a property or method that allows you to access the data passed from the main form. In the suggested solution, a constructor is used to pass the string to the settings form. This constructor will store the string in a private member variable, which can then be accessed through a public getter method.
Complete Code Example
The complete code example is as follows:
MainForm.cs
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(SomeString); settingsForm.ShowDialog(); } private void OnPageInfoRetrieved(PageInfoEventArgs args) { if (PageInfoRetrieved != null) PageInfoRetrieved(this, args); } }
SettingsForm.cs
public class SettingsForm : WinForm { private string m_Data; public SettingsForm(string data) { m_Data = data; } public string Data { get { return m_Data; } } }
The above is the detailed content of How Can I Pass Data Between Windows Forms Using Delegates and Event Handlers?. For more information, please follow other related articles on the PHP Chinese website!