Dynamically adding controls in ASP.NET Repeater

2020-02-08 21:20发布

I find my self having a repeater control which is being databound to an xml document. My client is now requesting that the Textbox's which are being repeater can be either a Textbox or a Checkbox.

I cannot seem to find an easyway to essentially do the following:

if ((System.Xml.XmlNode)e.Item.DataItem.Attributes["type"] == "text")
<asp:TextBox runat="server" ID="txtField" Text='<%#((System.Xml.XmlNode)Container.DataItem).InnerText %>' CssClass="std"></asp:TextBox>
else
<asp:CheckBox runat="server" ID="txtField" Text='<%#((System.Xml.XmlNode)Container.DataItem).InnerText %>' CssClass="std"></asp:TextBox>

Is there a nice way I can extend my current implementaion without have to rewrite the logic. If I could inject the control via "OnItemDataBound" that would also be fine. But I cannot seem to make it work

3条回答
Rolldiameter
2楼-- · 2020-02-08 21:58

In your repeater, drop a Panel, then create an event handler for the repeater's data binding event and programmatically create the TextBox or CheckBox and add it as a child control of the Panel. You should be able to get the DataItem from the event args to get information like your "type" attribute or values to feed your Text properties or css information, etc.

查看更多
神经病院院长
3楼-- · 2020-02-08 22:17

I would go with mspmsp's sugestion. Here is a quick and dirty code as an example of it:

Place this in your aspx:

<asp:Repeater ID="myRepeater" runat="server" OnItemCreated="myRepeater_ItemCreated">
    <ItemTemplate>
        <asp:PlaceHolder ID="myPlaceHolder1" runat="server"></asp:PlaceHolder>
        <br />
    </ItemTemplate>
</asp:Repeater>

And this in your codebehind:

dim plh as placeholder
dim uc as usercontrol
protected sub myRepeater_ItemCreated(object sender, RepeaterItemEventArgs e)
    if TypeOf e Is ListItemType.Item Or TypeOf e Is ListItemType.AlternatingItem Then
        plh = ctype(e.item.findcontrol("myPlaceHolder1"), Placeholder)
        uc = Page.LoadControl("~/usercontrols/myUserControl.ascx")
        plh.controls.add(uc)
    end if
end sub
查看更多
再贱就再见
4楼-- · 2020-02-08 22:20

What about something similar to this in your markup in each the textbox and checkbox controls?

Visible=<%= Eval("type").tostring() == "text") %>
查看更多
登录 后发表回答