Passing Data Between Windows Forms Using Delegates
In a Windows Forms application, when working with multiple forms, it often becomes necessary to pass data between them. A common approach to achieve this is through delegates. Here's how you can implement data passing using delegates:
Creating the Delegate
First, you need to create a delegate that will serve as the callback method for data transfer. In C#, this can be done as follows:
public delegate void PageInfoHandler(object sender, PageInfoEventArgs e);
This delegate declares a method that takes two parameters: a sender object (typically the form sending the data) and an event argument object (which contains the actual data).
Using the Delegate
Within the main form, you can create an instance of the delegate and raise the event whenever you want to pass data to the child form. For example:
public partial class MainForm : Form { // Declare the delegate instance public event PageInfoHandler PageInfoRetrieved; private void toolStripBtnSettings_Click(object sender, EventArgs e) { PageInfoEventArgs args = new PageInfoEventArgs(SomeString); this.OnPageInfoRetrieved(args); SettingsForm settingsForm = new SettingsForm(); settingsForm.ShowDialog(); } private void OnPageInfoRetrieved(PageInfoEventArgs args) { if (PageInfoRetrieved != null) PageInfoRetrieved(this, args); } }
Retrieving the Data
Within the child form (in this case, the SettingsForm), you can subscribe to the delegate event to receive the data. This can be done in the child form's constructor or in its initialization code. For example:
public class SettingsForm : Form { public SettingsForm() { // Subscribe to the delegate event if (MainForm.PageInfoRetrieved != null) MainForm.PageInfoRetrieved += new PageInfoHandler(OnPageInfoRetrieved); } private void OnPageInfoRetrieved(object sender, PageInfoEventArgs e) { // This method will be called when the PageInfoEventArgs is raised // in the main form. You can access the data from the event argument here. // ... } }
Using the Data
Once you have retrieved the data in the child form, you can use the provided event arguments to access the actual data. In this example, the data is passed as a property of the PageInfoEventArgs object. For instance, you could use it like this:
// In the SettingsForm private void DisplayData() { // Get the data from the event arguments string data = e.Data; // Display or use the data in the child form // ... }
By following these steps, you can efficiently pass data between multiple Windows Forms using delegates, enabling communication and data exchange between forms in your application.
The above is the detailed content of How to Pass Data Between Windows Forms Using Delegates?. For more information, please follow other related articles on the PHP Chinese website!