views:

30

answers:

1

ref: Dynamic Control ID

Does anyone have a working example of creating the ID property of a hyperlink dynamically?

I have a repeater with multiple hyperlinks drawn (3 per row for a survey). I would like to change the image of the hyperlink clicked. The repeater is created from its bound datasource. Cant get it working

EDIT:I used your example and it does change the image, however it changes all the ID="HappyLink" items instead of the one selected.

    // if the happy emoticon was clicked
    if (this.Request.QueryString["hyperlink"] == "HappyLink")
    {
        HyperLink happylink = e.Item.FindControl("HappyLink") as HyperLink;

        if (happylink != null)
        {
            happylink.ImageUrl = "~/images/happy_selected.jpg";
        } // if (happylink != null)
    } // if (this.Request.QueryString["hyperlink"] == "HappyLink")
A: 

I don't think you need to worry about dynamic IDs. The Repeater control sorts out the IDs for you, you don't need to care what they are.

If you mean that each Hyperlink is an image, then you need to handle the ItemDataBound event of the Repeater. In the markup, you give the Hyperlink an ID. In the ItemDataBound event handler, you use the FindControl method on the Item object you get from the event argument, passing the ID of the Hyperlink. This will give you the actual hyperlink control. Then just set the image.

For example:

void Repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
   HyperLink hyperLink = e.Item.FindControl("HappyLink") as HyperLink;
   if (hyperLink != null)
   {
      // do something with the hyperlink
   }
}

In the FindControl method, you just use the ID you set in the markup. The use of e.Item ensures you get the hyperlink from the right row of the repeater.

Graham Clark
Thanks for your reply. I have the 3 hyperlink controls (HappyLink,OkLink,FailLink) in the repeater and they all loop accordingly. However, the ID that I give them is the same for all the databound items that I have. I understand that the ID changes to something like Repeater1_ctl01_HappyLink. How do I use the FindControl method to find the 5th row's first icon when clicked? e.g. Repeater1_ctl05_HappyLink. I come from a PHP background, so please bear with me
Thomas
@Thomas: I've added an example, hopefully this makes things clearer.
Graham Clark