Events on controls in web server control
I'm creating a web server control that has an image button on it. The html for the control is done in the RenderControls of the code, the control devrives from WebControl, IScriptControl, INamingContainer.
The b开发者_StackOverflow中文版utton is coded as follow in the RenderControls:
System.Web.UI.WebControls.ImageButton img = new System.Web.UI.WebControls.ImageButton();
img.ImageUrl = "Url of the image";
img.Click += new ImageClickEventHandler(img_Click);
img.ID = this.ClientID + "_img";
img.CausesValidation = false;
imgLock.RenderControl(output);
The button apreas in the browser but when i click on it, the page postsback but the event handler for the button doesn't get fired, from what i can figure out, since the control goes throught RenderControls eachtime the page is posted back, the button gets redrawn and the event handling disapears.
This server control is in a master page.
Anyone can help me on this?
Thanks
When you postback data in asp.net, will follow different phases:
1.Initialization, 2.LoadViewState 3.LoadPostData 4.ObjectLoad
During the phase 3 (LoadPostData) the framework will implement the IPostBackDataHandler interface on each control that submitted data.
The page then fires the LoadPostData event and will match each control that implements this interface with the correct postback data.
This means that you need to Create the control before the Asp.net arrives at stage (LoadPostData).
My suggestion is to create the control at the Page_Init, this away you will not lose the events e.g. (Click).
Could it be that your Button's ID changes between postbacks?
img.ID = this.ClientID
...looks strange. Replace it with img.ID = "MyButtonID" or something like that.
WebControl must be created and have attached event handlers after page Load event to handle any input from user.
You should try to create ImageButton, setup event hanlers and add it to Controls collection in overridden method OnLoad.
protected override void OnLoad(EventArgs e)
{
System.Web.UI.WebControls.ImageButton img = new System.Web.UI.WebControls.ImageButton();
img.ImageUrl = "Url of the image";
img.Click += new ImageClickEventHandler(img_Click);
img.ID = this.ClientID + "_img";
img.CausesValidation = false;
this.Controls.Add(img);
}
精彩评论