There are lots of ways to use Delegate in C#. Shown below only 2 ways of how to use Delegate to communicate between UserControl & Form.
1. Using Event-Delegate:
Inside UserControl the code will be like below:
// using event - delegate
public delegate void MyDelegate(string str);
public event MyDelegate MyEvent;
private void button1_Click(object sender, EventArgs e)
{
// event that will be fire from usercontrol & catch by form
MyEvent("SAJAL");
}
Inside Form the code will be like below:
// attach method to fire
this.userControl11.MyEvent += new UserControl1.MyDelegate(MyMethod);
void MyMethod(string str)
{
this.textBox1.Text = str;
}
2. Using Delegate:
Inside UserControl the code will be like below:
// using only delegate
public delegate void MyDelegate(string str);
public MyDelegate NewMyDelegate;
// need to store the delegate
public void FireMe(MyDelegate md)
{
NewMyDelegate = md;
}
private void button1_Click(object sender, EventArgs e)
{
NewMyDelegate("BAPPY");
}
Inside Form the code will be like below:
// attach method to fire
this.userControl11.FireMe(new UserControl1.MyDelegate(MyMethod));
void MyMethod(string str)
{
this.textBox1.Text = str;
}
The basic difference is to use an extra method for Number 2.
Wednesday, May 21, 2008
Subscribe to:
Post Comments (Atom)
2 comments:
just a quick thought... but easy to understand. nice article!
Great ! Easy to implement
Post a Comment