Monday 13 February 2012

dynamic user control in asp.net

PressMe
PressMe1
DESIGN CODE:
asp:UpdatePanel ID="up" runat="server">
contenttemplate>
asp:PlaceHolder ID="ph" runat="server">
/ContentTemplate>
triggers>
asp:AsyncPostBackTrigger ControlID="btn" EventName="Click" />
/Triggers>
/asp:UpdatePanel>
asp:Button ID="btn" runat="server" Text="Add More" Width="80" onclick="btn_Click" />
div>
asp:UpdatePanel ID="up1" runat="server">
contenttemplate>
asp:Button ID="btn1" runat="server" Text="Display" Width="80"
onclick="btn1_Click" />

asp:Label ID="lb" runat="server">
/ContentTemplate>
/asp:UpdatePanel>
C# CODE :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
static int myCount = 0;
private UserControl[] dynamicTextBoxes;
protected void Page_PreInit(object sender, EventArgs e)
{
Control myControl = GetPostBackControl(this.Page);

if ((myControl != null))
{
if ((myControl.ClientID.ToString() == "btn"))
{
myCount = myCount + 1;
}
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
dynamicTextBoxes = new UserControl[myCount];
int i;
for (i = 0; i < myCount; i += 1)
{
UserControl uc = (UserControl)LoadControl("WebUserControl.ascx");
uc.ID = "uc" + i.ToString();
ph.Controls.Add(uc);
dynamicTextBoxes[i] = uc;
LiteralControl literalBreak = new LiteralControl("
");
ph.Controls.Add(literalBreak);
}
}
public static Control GetPostBackControl(Page thePage)
{
Control myControl = null;
string ctrlName = thePage.Request.Params.Get("__EVENTTARGET");
if (((ctrlName != null) & (ctrlName != string.Empty)))
{
myControl = thePage.FindControl(ctrlName);
}
else
{
foreach (string Item in thePage.Request.Form)
{
Control c = thePage.FindControl(Item);
if (((c) is System.Web.UI.WebControls.Button))
{
myControl = c;
}
}

}
return myControl;
}
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btn_Click(object sender, EventArgs e)
{

}
protected void btn1_Click(object sender, EventArgs e)
{
lb.Text = "";
foreach (UserControl tb in dynamicTextBoxes)
{
string s = ((TextBox)tb.Controls[0]).Text;
lb.Text +=s + " :: ";
}
}
}

No comments:

Post a Comment