I have create a userControl name is UserControl1. On this usercontrol, I create a button name is btnAdd. I create 2 form name are Form1 and Form2. And then I add UserControl开发者_JAVA技巧1 on those form. I want to when I click btnAdd button on Form1 then show string "this is form 1", if I click btnAdd button on Form2 then show string "this is form 2".
I want to use delegate and event to do that. Could you help me. Thank you very much.
My code following but not run. the true result must show on messagebox "add successful":
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace EventDelegateUserControl
{
public partial class UC_them : UserControl
{
public UC_them()
{
InitializeComponent();
}
public delegate void ThemClickHandler(object sender, EventArgs e);
public event ThemClickHandler ThemClick;
public void OnThemClick(EventArgs e)
{
if (ThemClick != null)
{
ThemClick(this,e);
}
}
public void add()
{
OnThemClick(EventArgs.Empty);
}
public void btnThem_Click(object sender, EventArgs e)
{
add();
}
}
//---------------------------
public partial class Form1 : Form
{
public UC_them uc_them =new UC_them();
public Form1()
{
InitializeComponent();
}
public void dangky(UC_them uc_them)
{
uc_them.ThemClick += new UC_them.ThemClickHandler(uc_them_ThemClick);
}
void uc_them_ThemClick(object sender, EventArgs e)
{
MessageBox.Show("Add successful");
}
}
//----------------------------
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
UC_them them = new UC_them();
Form1 form1 = new Form1();
form1.dangky(them);
}
}
}
Your delegate/event related code is correct. The issue with the Main method.
Application.Run(new Form1());
UC_them them = new UC_them();
Form1 form1 = new Form1();
form1.dangky(them);
You create two instances of Form1 in the the main method. One instance in the Application.Run(first instance) method and create another instance after that. You set the event binding only for the second instance. But actually only the first instance is running.
If you change your main method as below it should work.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
UC_them them = new UC_them();
Form1 form1 = new Form1();
form1.dangky(them);
Application.Run(form1);
}
精彩评论