Reputation: 11469
I have a User Control with with some search functionality, then I also have a control that contains a grid. In the control that has the grid I have all the functionality to retrieve some items I need to populate a report from the search control.
My question is, and I have read about this but not completely sure how to make it work, I read i need to register a event handler in control A that calls the function in control B. How does that work?
Say in control B there is a function that I need to call GetAllItemsByRegistrantID(int id).
How can I make a call to this function from control A?
I would really appreciate any help or guidance on this.
Regards
Upvotes: 0
Views: 117
Reputation: 82489
Here is an example if you had to do it using events.
On your first user control (the search control) define a custom event.
public partial class UserControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public event EventHandler<MyCustomeEventArgs> MyCustomClickEvent;
protected virtual void OnMyCustomClickEvent(MyCustomeEventArgs e)
{
if (MyCustomClickEvent != null)
MyCustomClickEvent(this, e);
}
public void button1_Click(object sender, EventArgs e)
{
OnMyCustomClickEvent(new MyCustomeEventArgs(5));
}
}
public class MyCustomeEventArgs : EventArgs
{
public MyCustomeEventArgs(int searchID)
{
SearchID = searchID;
}
public int SearchID { get; set; }
}
On your user control with the grid, define a handler.
public void HandleCustomEvent(object sender, MyCustomeEventArgs e)
{
GetAllItemsByRegistrantID(e.SearchID);
}
public void GetAllItemsByRegistrantID(int id)
{
Label1.Text = id.ToString();
}
On the page where they both live, wire them together.
protected void Page_Load(object sender, EventArgs e)
{
UserControl1Instance.MyCustomClickEvent += UserControl2Instance.HandleCustomEvent;
}
Upvotes: 3
Reputation: 6587
I would definitely try and avoid this sort of situation. You should be putting this sort of code in a class and sharing this between the two controls.
Upvotes: 0