Add a usercontrol to itself declaratively?

J

Jos

Can you add a user control recursively to itself?

Imagine some kind of tree control, where every node is again a tree control.

Each node is populated with a DataList containing the child nodes.

I manage to add additional instances of the user control to the
item template in the ItemDataBound handler, like this:

Sub DataList1_ItemDataBound(sender As Object, e As
DataListItemEventArgs)
If(e.Item.ItemType=ListItemType.Item Or
e.Item.ItemType=ListItemType.AlternatingItem) Then
Dim testControl1 As New TestControl()
e.Item.Controls.Add(testControl1)
testControl1.BindDataList1()
End If
End Sub

In order to have a class name, I use this Control directive:
<%@ Control Language="VB" ClassName="TestControl" %>

This works perfectly.

But my question is: can I add the user control to the ItemTemplate
declaratively instead of programmatically, like this:

<asp:DataList id="DataList1" OnItemDataBound="DataList1_ItemDataBound"
runat="server">
<ItemTemplate>
<TestControl id="testControl1" runat="server" />
</ItemTemplate>
</asp:DataList>

This still gives me no error, but now I need to refer to the control for
binding.

I try to bind it like this:
Sub DataList1_ItemDataBound(sender As Object, e As
DataListItemEventArgs)
If(e.Item.ItemType=ListItemType.Item Or
e.Item.ItemType=ListItemType.AlternatingItem) Then
Dim testControl1 As TestControl =
CType(e.Item.FindControl("testControl1"),TestControl)
testControl1.BindDataList1()
End If
End Sub

I get the error: specified cast is not valid.

How can I get this cast to work?

Thanks for your help,

Jos
 
V

Victor Garcia Aprea [MVP]

Hi Jos,

Please debug your code and check what is the FindControl call returning...
that should give you a good clue of what may be wrong,

--
Victor Garcia Aprea
Microsoft MVP | ASP.NET
Looking for insights on ASP.NET? Read my blog:
http://obies.com/vga/blog.aspx

a) If you're looking
 
J

Jos

Victor said:
Hi Jos,


Please debug your code and check what is the FindControl call
returning... that should give you a good clue of what may be wrong,

It returns "HtmlGenericControl".

I guess what's wrong is that ASP.NET can't handle the tag
properly, because it is recursive.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,527
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top