kyurkchyan
kyurkchyan

Reputation: 2428

Bind control's ID property to object property

I have the following repeater control, which is bound to collection of DashboardPage objects. DashboardPage has the following properties: Name, Pagenumber .

<asp:Repeater ID="reportPages" runat="server">           
      <ItemTemplate>
        <asp:ImageButton    runat="server" onclick="ImageButton_Click" 
        ImageUrl="<%# GetImagePath(Container.DataItem) %>" 
        onmouseover="<%# GetMouseOverEventString(Container.DataItem) %>"
        onmouseout="<%# GetMouseOutEventString(Container.DataItem) %>"
         />
      </ItemTemplate>

      <SeparatorTemplate>
        &nbsp;&nbsp;
      </SeparatorTemplate>
  </asp:Repeater>

I want to bind ImageButton's ID property to Name property of DashboardPage object, something like this

ID="<%# Eval('Name') %>"

But an exception is thrown:

The ID property of a control can only be set using the ID attribute in the tag and a simple value.

I need the ID property of the image, because I have a client side script which changes the image, using the it's ID. Is there a way around this?

Thanks for replies

Regards Gagik Kyurkchyan

Upvotes: 0

Views: 2440

Answers (2)

Antonio Reyes
Antonio Reyes

Reputation: 536

You can use ItemDataBound to set the ID.

CODEBEHIND:

protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    var textbox = e.Item.FindControl("myTextBox");
    textbox.ID = "myTextBox" + (e.name).toString(); /*ToString() method can be unnecessary in some cases.*/
}

REPEATER:

<asp:Repeater ID="myRepeater" runat="server" OnItemDataBound="BehaviorCustomizeRepeater_ItemDataBound">
/*other stuffs*/
</asp:Repeater>

Upvotes: 0

Dan Diplo
Dan Diplo

Reputation: 25339

Since you have found you cannot dynamically set the ID of a server control you need to find an alternative way of referencing your image using JavaScript. There are three ways I can think of:

  1. Set the CssClass property of the control and use that instead. It's a little more inefficient to find a control by class rather than ID using DOM, but that is probably negligible in the real world.

  2. Wrap your image in a standard DIV. and set the ID on the container DIV. You can then use something like jQuery to go $("#divid img")...

  3. Use a standard <img> tag (with no runat="server") rather than an asp:Image control. You can then set the ID on that without issue.

Upvotes: 2

Related Questions