Accessing asp controls within a datalist
Question
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>
Solution
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...
OTHER TIPS
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
same you can do with labels and hyperlinks
private void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
{
ImageButton imgbutton = (ImageButton)e.Item.FindControl("imgbtnTitle");
imgbutton.ToolTip = "abc";
}
}
Yes, you can access the asp controls inside the datalist by using the Datalist Item Data bound
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
HyperLink TitleLink = (HyperLink)e.Item.FindControl("lnkTitle");
}
}