Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  


Adding Events to Controls within a Custom .NET WebControl
In a basic WebControl, you can override RenderContents to generate the look & feel of the control dynamically.

Sometimes you may want to use controls within a control, such as multiple buttons.

If you create a button and render it in RenderContents, it will create the button, but there is no way to listen to events such as the Click Event. You can click the button, but nothing happens.

You may think to render the button in the OnLoad, and register the event at the same time. This works until you have a page that dynamically creates the button AFTER the page OnLoad, such as if you rendered the control within a datagrid in response to a button click; OnLoad is fired before the content is rendered, so your properties such as Text, Width, BackColor, etc, may not get set to what you expect.

So a solution that works for both of these scenarios:

1. Make sure the child controls are actual objects instantiated in the WebControl:

public class MyCustomControl: WebControl
Button myButton = new Button();
Button myOtherButton = new Button();

2. Forget about RenderContent. Use CreateChildControls to set any properties of your children, such as Text, Visible, Width, etc. Don't set the events. This ensures they are set as late as possible. If you're still having trouble, set the values whenever the property changes, or make a public LoadData() method to get total control over when these are created.
protected override void CreateChildControls()
myButton.Text = this.CustomButtonText;
myOtherButton.Visible = this.ShowOtherButton;

3. Override OnLoad to ensure your events are registered. This ensures they're registered once for each page load.
protected override void OnLoad(EventArgs e)
myButton.Click += new EventHandler(someButton_Click);
myOtherButton.Click += new EventHandler(someButton_Click);

4. Create your event handlers
void someButton_Click(object sender, EventArgs e){}

You can handle the event, or you may wish to propogate it up to the web page. For the latter, refer to my other post on creating events in controls if you'd like.

Created By: amos 9/24/2013 5:25:47 PM