Sunday, March 11, 2012

Need to add some controls dynamically via AJAX

Hi,
???Here is a sample to load controls to the ContentTemplate?of a asp:UpdatePanel for your reference.
??well, here's a small sample that should get you started (i'm only creating textboxes, but i think you can extend it so that it supports other kinds of controls (btw, in a real sample, i'd give the contorl an id and would persist it to so that when the control gets recreated, it's correctly updated.

<%@. Page Language="C#" %
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
<script runat="server">
void AddTxt(object sender, EventArgs e)
{
TextBox txt = new TextBox();
holder.Controls.Add(txt);

if (Session["ctls"] != null)
{
Session["ctls"] += ";t";
}
else
{
Session["ctls"] = "t";
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);

if (Session["ctls"] != null)
{
string[] ctls = Session["ctls"].ToString().Split(';');
foreach( string ctlType in ctls)
{
if( string.Compare(ctlType, "t") == 0)
{
holder.Controls.Add(new TextBox());
}
}
}
}

</script
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:scriptmanager runat="server" id="manager" />
<asp:UpdatePanel runat="server" ID="panel">
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="holder"></asp:PlaceHolder>
<asp:Button runat="server" ID="bt" Text="Add" onclick="AddTxt" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Wish the above can give you some helps.

Thanks for your answer

But this solution is not for my case!

This update content of the UpdatePanel and data of the TextBoxes is resotring from ViewState. In my case are a lot of Data which can't be restored from ViewState.

No comments:

Post a Comment