views:

29

answers:

3

Hi All,

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 button 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

A: 

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);
 }
the vk
Thanks for your suggestion. I tried this and i get the same result.
MarkyMarc
A: 

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.

Tim Schmelter
I tried a static name for the button, same result.
MarkyMarc
+1  A: 

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).

Pedro Tiago Pereira
Since the button is in a web server control added to a master page, how would i be able to use the page_init?
MarkyMarc
Actually after a bit more research, i changed my server control to create its child control to the OnInit event and now it works.So thanks for getting me on the right track
MarkyMarc