Search code examples
asp.netrepeater

Set IDs of controls of a repeater


I have a repeater that contains a few controls and I want to set their ID's based on the IDs from database. The datasource of the repeater is a list so basicly I want to do something like this in code behind, in repeater_ItemDataBound():

var myControl = e.Item.FindControl("controlID");
myControl.ClientIDMode = ClientIDMode.Static;
myControl.ID = e.Item.DataItem("ID"); //but I can't access the ID property, so here's my problem.

considering that I declared my repeater something like:

<asp:Repeater ID="repeater" runat="server">
    <ItemTemplate>
            <div class="someClass">
               <asp:Label ID="controlID"  runat="server"><%# Eval("Name")%></asp:Label>
               <!-- list of other controls -->
            </div>
    </ItemTemplate>
</asp:Repeater>

Solution

  • Don't change ID's of controls that were already created with a different ID. That could cause nasty errors. Instead use the right ID in the first place. Or use whatever ID you use and assign the identifier to a different property like CommandArgument if it's a Button, Value if it's a HiddenField or Text if it's an (invisible) TextBox or Label.

    So in this case you could use another control to store the ID:

    <asp:HiddenField ID="hiddenID" runat="server" Value='<%# Eval("ID")%>' />
    <asp:Label ID="lblName"  runat="server"><%# Eval("Name")%></asp:Label>
    

    Now, if you need the ID of the current item and you have the reference of the label or another control in that repeater-item:

    var item = (RepeaterItem) lblName.NamingContainer;
    HiddenField hiddenID = (HiddenField) item.FindControl("hiddenID");
    string id = hiddenID.Value;