Dynamically adding controls in ASP.NET Repeater

早过忘川 提交于 2019-11-27 14:13:38

问题


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


回答1:


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

Visible=<%= Eval("type").tostring() == "text") %>



回答2:


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:


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


来源:https://stackoverflow.com/questions/128083/dynamically-adding-controls-in-asp-net-repeater

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!