Finding control in DataList itemBound

  • Thread starter Thread starter neverstill
  • Start date Start date
N

neverstill

Hi-
I have an asp:image control in the ItemTemplate of a DataList
currently, in the ItemDataBound event, I am getting a reference to the image
control by looping through all the controls in the DataItem and checking if
it is an image control. This is ugly. I can't use "FindControl" cause I
don't know the ID as it is changed each time. I guess I could do some
tricky string work, but that would not be full proof.

Is there an easy way to get a control that is dynamically created at runtime
like this?

Any ideas?

Thanks,
Steve
 
Hi,

Couldn't you reference it with an index from Controls collection?

Why does the ID change, by the way? As every DataListItem is naming
container for its child controls, they can all have controls with the same
ID say

<ItemTemplate>
<asp:Image ID="myImage" runat="server" />
</ItemTemplate>

even if the Image would be created somehow dynamically in code, this should
work fine. You can in ItemDataBound reference them separately per item (as
you know I suppose, but I am wondering why the ID changes)
 
actually, you pointed out a major oversight on my part. I inspected the
result rendered HTML and noted that the ID values for each image had
changed, but it appears that in the ItemDataBound, they are not, they are
the same.. as you stated.

So, FindControl() works just great. I never even tried it, thought I was
being efficient and working around something that didn't need to be worked
around. ;)

Thanks!
 
Hi,

that is because the control is in naming container and controls inside
different naming containers can have same IDs. As a result, ClientID and
UniqueID reflect the position in the control tree, but ID itself stays the
same despite the position (hierarchically in containers and so on)

FindControl method always looks inside the current naming container (you
search for the current DataListItem, naming container, in ItemDataBound when
you use e.Item.FindControl) and as IDs are same there in every item, using
the plain ID with FindControl works fine.

Glad to know I could help you!
 
Back
Top