如何在自己内部嵌套ASP.Net用户控件?

时间:2012-06-13 19:17:11

标签: c# asp.net vb.net user-controls

我认为简短的回答是你做不到,但必须有一些方法来实现它。我想制作一个项目列表,然后列出其中的项目列表,只嵌套一个级别。即:

 Repeater  
    UserControl1  
        UserControl1  
        UserControl1  
    UserControl1
        UserControl1  
    UserControl1  
    UserControl1  

我真的很想避免使用LoadControl,因为我正在服务器端添加到此列表中单击事件,因此我无法在PageInit上执行loadControl以使所有视图状态的东西起作用。

我将尝试编写一个快速的伪代码示例,它看起来像这样:

Page.aspx

<asp:repeater runat="Server" id="someRepeater">
<uc:UserControl1 runat="Server" id="ctrlParent" />
</asp:repeater>

UserControl1.ascx

<asp:label id="label1" runat="server" />
<asp:repeater runat="server" id="childRepeater">
    <uc:UserControl1 runat="server" id="ctrlChild" />
</asp:repeater>

UserControl1.ascx.vb

If me.HasChildren then
    'BindChildRepeater'
end if

sub Fill(Data as RelevantData)
    label1.Text = Data.SomeText
end sub

sub ChildRepeater_ItemDataBound(object as sender, e as someArgs)
    Dim childCtrl = e.item.findcontrol("ctrlChild")
    childCtrl.Fill(e.item.dataitem)
end sub

3 个答案:

答案 0 :(得分:2)

您可以将转发器嵌套在转发器中

<asp:repeater runat="Server" id="someRepeater1">
    <uc:UserControl1 runat="Server" id="ctrlParent1" />
    <asp:repeater runat="Server" id="someRepeater2">
        <uc:UserControl1 runat="Server" id="ctrlParent2" />
    </asp:repeater>
</asp:repeater>

答案 1 :(得分:0)

只需调用用户控件中要调用另一个用户控件的<%@ Register src="" tagname="" tagprefix=""%>。在另一个用户控件中调用用户控件就像在普通的aspx页面中调用用户控件一样。

答案 2 :(得分:0)

这就是我所做的。基本上你使用LoadControl添加的控件将在回发后消失,所以我所做的只是在Page_Load

回发期间调用此函数
Private Sub AddSubCategorizedQuestionItemControls()

    If rptSubCategorizedquestionList.Items IsNot Nothing AndAlso
        rptSubCategorizedquestionList.Items.Count > 0 Then

        For Each _item As RepeaterItem In rptSubCategorizedquestionList.Items

            If _item.ItemType = ListItemType.AlternatingItem OrElse
                     _item.ItemType = ListItemType.Item Then

                Dim _hfCategoryID As HiddenField = _item.FindControl("hfCategoryID")

                Dim _placeHolderSubCategoryQuestionItem As PlaceHolder = _item.FindControl("placeHolderSubCategoryQuestionItem")

                Dim _nestedCategorizedListItemControlUserControlObject As UserControl =
                                                                LoadControl("__categorizedQuestionListItem.ascx")

                _nestedCategorizedListItemControlUserControlObject.ID =
                                      String.Format("ucCategorizedQuestionListItem", _hfCategoryID.Value)

                _placeHolderSubCategoryQuestionItem.Controls.Add(_nestedCategorizedListItemControlUserControlObject)

                Dim _nestedCategorizedListItem As Common_Questions__categorizedQuestionListItem =
                    DirectCast(_nestedCategorizedListItemControlUserControlObject, Common_Questions__categorizedQuestionListItem)

            End If

        Next

    End If

End Sub