Hi, I have on my Page a Label control and custom UserControl. I want that, when something appears in the UserControl, it shoud change e.g the Label's Text property (as I mentioned, the Label doesn't belong to the UserControl). How to do that ?
A UserControl should be re-usable, so to do this correctly, you should use an event from the UserControl that the Page hooks into, i.e:
public NewTextEventArgs : EventArgs
{
public NewTextEventArgs(string newText)
{
_newText = newText;
}
public NewText
{
get { return _newText; }
}
}
Then add the following event to your UserControl:
public event OnNewText NewText;
public delegate void OnNewText(object sender, NewTextEventArgs e);
Then to fire the Event from the user control:
private void NotifyNewText(string newText)
{
if (NewText != null)
{
NewText(this, new NewTextEventArgs(newText));
}
}
Then just consume that Event on your Page and the UserControl and Page are no longer tightly coupled:
Then handle the event and set the text to your Label:
protected void YourControl1_NewText(object sender, NewTextEventArgs e)
{
Label1.Text = e.NewText;
}
Your best bet is to use some sort of event to notify the containing page that the UserControl was updated.
public class MyControl : UserControl {
public event EventHandler SomethingHappened;
private void SomeFunc() {
if(x == y) {
//....
if(SomethingHappened != null)
SomethingHappened(this, EventArgs.Empty);
}
}
}
public class MyPage : Page {
protected void Page_Init(object sender, EventArgs e) {
myUserControl.SomethingHappened += myUserControl_SomethingHappened;
}
private void myUserControl_SomethingHappened(object sender, EventArgs e) {
// it's Business Time
}
}
This is just a basic example, but personally I recommend using the designer interface to specify the user control's event handler so that the assignment gets handled in your designer code-behind, rather than the one you're working in.
You can dot that by raising an event from your custom UserControl. The page can then intercept the event and modify the label's Text property accordingly:
You can use Page property to access page contain of the UserControl. Try:
((Page1)this.Page).Label1.Text = "Label1 Text";