tags:

views:

59

answers:

2

Say I have a User Control in ASP.NET that contains a button:

public class MyUserControl : UserControl {
    private Button btnSave = new Button();
}

I can expose any property of the button to the outside by making a property that points at the button:

public string SaveButtonText { 
    get { return btnSave.Text; } 
    set { btnSave.Text = value; } 
}

So then I can do this to set the button's text:

MyControl.SaveButtonText = "hello world";

Is there a similar construct I can use to expose the button's events to the outside as well? Something like:

public event SaveButtonClick { return btnSave.OnClick; }
...
MyControl.SaveButtonClick += new EventHandler(...);
+2  A: 
    public event EventHandler SaveButtonClick {
        add { btnSave.Click += new EventHandler (value); }
        remove { btnSave.Click-= new EventHandler (value); }
    }
JeffN825
+5  A: 

You can do something like that, yes:

public event EventHandler SaveButtonClick
{
    add { btnSave.Click += value; }
    remove { btnSave.Click -= value; }
}

Note however that there's one downside to this - the "sender" argument supplied to the event handlers will still be the save button rather than your control... that may not be what the subscriber expected. An alternative approach is to subscribe once to the save button's click handler yourself:

public event EventHandler SaveButtonClick = delegate {};

private void OnSaveButtonClicked(object sender, EventArgs e)
{
    // Replace the original sender with "this"
    SaveButtonClick(this, e);
}
...
btnSave.Click += OnSaveButtonClicked();

There's a downside to this approach too... you end up having a reference from the save button to "this" all the time, which may have an impact on garbage collection. Basically your control won't be able to be garbage collected until the save button is also eligible for garbage collection. In this case I very much doubt that it's an issue, but it's worth being aware of.

Jon Skeet
Works great! Thanks
MisterZimbu