- The best way to communicate from UserControl to Page/MasterPage is using events
- The best way to communicate from MasterPage to Page is using events
On this way you don't hardlink UserControls with their Pages/MasterPages and the Page with it's Master.
Add an event to your UserControl that is raised when the user clicks the button, for example:
In UserControl of type MyControl
:
public delegate void SubmittedHandler(MyControl ctrl);
public event SubmittedHandler Submitted;
protected void BtnCLick(object sender, EventArgs e) {
Submitted(this);
}
Then add an handler to this event in your MasterPage, handle it and raise the Master's event again:
In Master's codebehind:
public delegate void MyControlSubmittedHandler(MyControl ctrl);
public event MyControlSubmittedHandler ControlSubmitted;
protected void Page_Init(Object sender, EventArgs e) {
this.MyControl1.Submitted += MyControlSubmitted;
}
protected void MyControlSubmitted(MyControl sender) {
ControlSubmitted(sender);
}
Then add an handler to this event to your page:
In your Page:
protected void Page_Init(object sender, EventArgs e) {
((SiteMaster)Master).ControlSubmitted += MasterControlSubmitted;
}
protected void MasterControlSubmitted(MyControl sender){
// do whatever you need to do
}
If you only need to access the TextBox
from the page and you don't need to handle the click-event, you could also use properties to achieve this:
- add a public property f.e.
MyControlText
in your UserControl
that get/set the TextBox.Text
property
- add a public property f.e.
MyControlText
in your Master
that get/set your UserControl's MyControlText
property
- Now you can get/set this property from your page in this way:
((SiteMaster)Master).MyControlText = "Hello World";