views:

312

answers:

2

How do you access an asp control within a datalist. For example, I would like to, but currently cannot, access the HyperLink control or the ImageButton control by inline code, or in the code-behind file.

<asp:DataList ID="DataList1" runat="server" AlternatingItemStyle-CssClass="altArtStyle">
        <HeaderTemplate>
            <table>
                <tr>
                    <td>
                        <asp:HyperLink ID="lnkTitle" runat="server" NavigateUrl="Default.aspx?order_by=title&direction=ASC" >

                        Title
                        </asp:HyperLink> <asp:ImageButton id="imgbtnTitle" src="/_images/hover-down.gif" runat="server"/>
                    </td>

                </tr>
            </table>
        </HeaderTemplate>
A: 

It depends. For example, if you wanted to change the header at runtime, in one of the object bind events, you'd do something like for this datalist header, do a findcontrol on the hyperlink and with that reference, do this...

Steve
Could you give me a short code example? I tried finding the control but got the complaint 'object reference not set to instance of object'. Heres the code I used after binding the data set. Dim imgbtnTitle As ImageButton = FindControl("imgbtnTitle") If imgbtnTitle.ImageUrl = "/_images/hover-down.gif" Then imgbtnTitle.ImageUrl = "/_images/hover.gif" ElseIf imgbtnTitle.ImageUrl = "/_images/hover.gif" Then imgbtnTitle.ImageUrl = "/_images/hover-down.gif" End If
contactmatt
Looks like Jason's got it covered. I'd only add that you might need to cast the control using CType. Take a look at: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.itemdatabound.aspx
Steve
A: 

Generally, you need to call FindControl on the DataListItem object, in order to find the control on the specific row. In your example, FindControl will only work on a header row, as in the following example:

Protected Sub DataList1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles DataList1.ItemDataBound
    If e.Item.ItemType = ListItemType.Header Then
        Dim btn As ImageButton = e.Item.FindControl("imgbtnTitle")
        If btn IsNot Nothing Then
            ' Do stuff here.
        End If
    End If
End Sub
Jason Berkan