Wednesday, March 28, 2012

Dynamic create UpdatePanel during postback

Hi,

I want to add a UpdatePanel into page dynamically during postback, see bellow code for detail. The problem is although UpdatePanel control was successful created, I cannot get its reference in later postback times.

// dummy template
publicclassMyTemplate :ITemplate
{
publicvoid InstantiateIn(Control container)

{

}

}

// create UpdatePanel during postback
protectedvoid Button5_Click(object sender,EventArgs e)
{

Microsoft.Web.UI.UpdatePanel u =new Microsoft.Web.UI.UpdatePanel();

u.ID ="udpDynamic";

u.ContentTemplate =newMyTemplate();

u.Mode = Microsoft.Web.UI.UpdatePanelMode.Conditional;

Microsoft.Web.UI.ControlEventTrigger trigger =new Microsoft.Web.UI.ControlEventTrigger();

trigger.ControlID ="Button6";// this button is created in design time

trigger.EventName =

"Click";

u.Triggers.Add(trigger);

this.Form.Controls.Add(u);

}

// other postback event
protectedvoid Button6_Click(object sender,EventArgs e)
{

Label test =newLabel();

test.Text ="I'm new portlet " +DateTime.Now.ToLongTimeString();

Microsoft.Web.UI.UpdatePanel u = (Microsoft.Web.UI.UpdatePanel)this.Form.FindControl("udpDynamic");

u.Controls.Add(test);// error! u is null

}

// here is HTML code generated, as I can see the UpdatePanel control was created successfully
<div id="udpDynamic"></div>

<components>
<pageRequestManager id="_PageRequestManager" updatePanelIDs="UpdatePanel1,UpdatePanel2,UpdatePanel3,udpDynamic" asyncPostbackControlIDs="Button4,Button6" scriptManagerID="ScriptManager1" form="form1" />
</components>

Well, I can't solve your problem, but I can tell you one thing that is wrong with your code:

When adding a control to an UpdatePanel, you need to use the ContentTemplateContainer.Controls.Add(...) property of the UpdatePanel, otherwise you will not see the control (in a book I read, it will actually throw an error, but I guess it isn't for you).

I work in VB.NET, although I can usually understand C#, but when I try to convert from System.Web.UI.Control (which is what FindControl returns) to System.Web.UI.UpdatePanel, I receive the following error message:

Unable to cast object of type 'System.Web.UI.Control' to type 'System.Web.UI.UpdatePanel'.

I am surprised that you are not receiving this error as well, if you take a look at my posting athttp://forums.asp.net/t/1154222.aspx you can see more details about this problem I am having. Good Luck!

No comments:

Post a Comment