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
Victor Garcia Aprea [MVP] - 24 Jun 2004 06:17 GMT
Hi Jos,
>>> Dim testControl1 As TestControl =
>>> CType(e.Item.FindControl("testControl1"),TestControl)
Please debug your code and check what is the FindControl call returning...
that should give you a good clue of what may be wrong,

Signature
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
> Can you add a user control recursively to itself?
>
[quoted text clipped - 51 lines]
>
> Jos
Jos - 26 Jun 2004 20:14 GMT
> Hi Jos,
>
[quoted text clipped - 3 lines]
> 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.

Signature
Jos