views:

1991

answers:

4

Hello all -

I have a custom control (compiled as a DLL) which loads a user control. (i.e, the custom control does a LoadControl) In the user control is a button and a textbox. I wire up the button's click event.

I type in a value into the text box. When I click the button, the page does a postback. My user control knows that a postback occured because Page.IsPostBack = true. However, the click event of the button is never fired and my text box has also lost the value that I typed in.

Anyone have any thoughts as to what might be going on?

EDIT: I did a test on this and took SharePoint out of the picture; I was able to reproduce it so I removed all references to SharePoint.

A: 

If you are databinding, you need to check that you are only doing so on !Page.IsPostBack when you databind, you wipe out any "saved" state from the postback.

Muad'Dib
I am not databinding. The page_load of the UC is empty.
Chu
A: 

Sounds like you're not recreating the control on postback. You will need to add the control during Page_Init for the view state to be loaded.

Adam
The custom control (the one I wrote as a DLL) is loaded to the page's Markup. ASP.NET is handling when it gets loaded... so I don't think this is the problem.
Chu
+1  A: 

If you are dynamically loading the user control, you have to reload it on each page load (postback or not) in order for the .net processor to know where to wire up the submit event.

Chris Lively
I am reloading it each time.
Chu
In the RenderContents section of the custom control.
Chu
I believe it is too late at that point. Controls should be loaded at or before Page_Load, preferably on OnInit.
Ruslan
Ok, I might be too new at Custom controls... Since I am loading a UserControl dynamically, using LoadControl, how would I "add" it ealier than that? I am basically using the HTML writer to get it on the page. Do I add it to the base.Controls collection to really "add" it?
Chu
Yes. Override the OnInit, Load and add it to the Controls collection. Wire any events that you may want to handle, such as button Click etc.
Ruslan
This ended up working. I overrode page init, then instead of having renderControls do the LoadControl, I looped through all the Controls and told each one to Render itself.Thanks for the help.
Chu
+1  A: 

One way to load the User Control is to override CreateChildControl, call base.CreateChildControls and then call your LoadControl method. If you need to place the UserControl is a specific location, place a PlaceHolder on the page and add your control to the place holders control collection.

You can also just add the user control directly to the markup.

Register the control as such:

<%@ Register Src="~/path/ControlName.ascx" TagName="tagName" TagPrefix="myPrefix" %>

and then add it in as follows:

<myPrefix:tagName ID="myId" runat="server"/>
Daniel