Groups | Blog | Home
all groups > asp.net > january 2008 >

asp.net : dynamically loading usercontrol


param@community.nospam
1/22/2008 11:09:09 PM
Hello all,

I have a UserControl that renders some HTML content. I now need to
dynamically load and render "n" instances of this usercontrol on a host aspx
page inside a panel control based upon user input of "n". Any ideas how I
can do this?

TIA!

Eliyahu Goldin
1/23/2008 10:45:44 AM
You need to use a databound control, perhaps a repeater, that will be bound
to a datasource, perhaps an array, containing all instances of the user
control.

Have some code that will creat an array myControls[] based on the user
input. Then do
myRepeater.DataSource = myControls;
myRepeater.DataBind();



--
Eliyahu Goldin,
Software Developer
Microsoft MVP [ASP.NET]
http://msmvps.com/blogs/egoldin
http://usableasp.net


[quoted text, click to view]

Milosz Skalecki [MCAD]
1/23/2008 12:37:02 PM
Howdy,

Use Repeater or DataList:

-- aspx code --
<asp:Repeater runat="server" ID="dynamicControls">
<ItemTemplate>
<uc1:myUserControl runat="server" ID="myUserControl"/>
</ItemTemplate>
</asp:Repeater>
-- c# code beside --
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int rowCount = 10;
myRepeater.DataSource = new int[rowCount];
myRepeater.DataBind();
}
}

Hope it helps
--
Milosz


[quoted text, click to view]
param@community.nospam
1/23/2008 5:34:56 PM
OK,

Thanks for the tip. Now, what if I need to set custom properties on my
usercontrol. Is that possible?

TIA!

[quoted text, click to view]

Milosz Skalecki [MCAD]
1/24/2008 10:37:01 AM
Howdy,

Yes it is, two ways:
1. through data binding:

<asp:Repeater runat="server" ID="dynamicControls">
<ItemTemplate>
<uc1:MyUserControl runat="server" ID="userControl" CustomDateProperty='<%#
DateTime.Now %>'/>
</ItemTemplate>
</asp:Repeater>

2. or in the code behind:
<asp:Repeater runat="server" ID="dynamicControls"
OnItemDataBound="dynamicControls_ItemDataBound">
<ItemTemplate>
<uc1:MyUserControl runat="server" ID="userControl" />
</ItemTemplate>
</asp:Repeater>
-- c# code behind --

protected void dynamicControls_ItemDataBound(object sender,
RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;

if (item.ItemType == ListItemType.Item ||
item.ItemType == ListItemType.AlternatingItem)
{
MyUserControl ctrl = (MyUserControlClassName)
item.FindControl("userControl");

ctrl.CustomDateProperty = DateTime.Now;
}

}

HTH
--
Milosz


[quoted text, click to view]
param@community.nospam
1/27/2008 11:47:54 AM
Thank you.

[quoted text, click to view]

AddThis Social Bookmark Button