Hi,
I am trying to implement an event to pass information to another form but am having issues trying to work out how to do it.
I have googled c# events and reviewed many of the returned results and they all seem overly complex and hard to understand and implement into the situation that I have.
My senario consists of a "Main" form ,from this form I open another popup form that shows a list of Contacts. On this form I have a button to add a new contact and when clicked it opens another popup form that shows the add Contact template.
What I would like to do is advise the "Main" form once save has been initiated on the "Add Contact Template" form.
Can anyone please advise and perhaps show a simple example of how to carryout the above.
Thanks in Advance
Peter
Loading
VulpesPosted Dec 13, 2013, 5:57 AM
/* add this class to your project */
class EventBroadCaster
{
public event EventHandler ContactAdded;
public void OnContactAdded(object sender, EventArgs e)
{
ContactAdded(sender, e); // broadcast event
}
}
/* make the highlighted change to program.cs */
static class Program
{
/* create global event broadcaster object */
internal static EventBroadCaster BroadCaster = new EventBroadCaster();
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
/* add the highlighted line to Form1 just before you open Form2 */
Program.BroadCaster.ContactAdded += this.ContactAdded; // subscribe to event
Form2 f2 = new Form2();
f2.ShowDialog();
/* add this handler to Form1 */
private void ContactAdded(object sender, EventArgs e)
{
MessageBox.Show("Contacted added!");
}
/* add this line to Form3 when a new contact is added */
Program.BroadCaster.OnContactAdded(this, EventArgs.Empty); // fire event
FroglegPosted Dec 12, 2013, 11:42 PM
Shankar MPosted Dec 12, 2013, 11:42 PM
This is one way to Pass data between Forms. You can follow other approaches like
Properties, Using objects to pass data or constructor approach, which suits your need.
Thanks,
M Shankar