views:

35

answers:

4

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 ?

+2  A: 

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;
}
GenericTypeTea
@Nathan Taylor - I removed the initial answer and replaced with a better event driven answer.
GenericTypeTea
Good stuff! Just a quick tip, with the generic EventHandler<T> there is no longer a need to create a delegate for your custom eventargs class. You can simply do `public event EventHandler<NewTextEventArgs> NotifyNewText;`
Nathan Taylor
@Nathan - Thanks. I didn't know that!
GenericTypeTea
+2  A: 

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.

Nathan Taylor
I thought so, but how catch this event on my Page ?
Tony
+1  A: 

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:

http://asp.net-tutorials.com/user-controls/events/

mamoo
A: 

You can use Page property to access page contain of the UserControl. Try:

((Page1)this.Page).Label1.Text = "Label1 Text";

MinhNguyen