smith269 smith269 - 1 month ago 8
ASP.NET (C#) Question

accessing controls in datalist headertemplate from codebehind

I have a datalist in my application whose headertemplate has a lable.Now i need to access the lable from codebehind.How can i do that..

CODE:

<asp:DataList ID="Dlitems" runat="server" RepeatDirection="Horizontal" RepeatColumns="4"
CellPadding="0" CellSpacing="15" OnItemCommand="Dlitems_ItemCommand">
<HeaderTemplate>
<asp:Label ID="lblcat" runat="server" Text="" />
</HeaderTemplate>


NOTE:I need to access the lable
lblcat
from headertemplate..

Answer

Attach OnItemDataBound event with your datalist like this

<asp:DataList ID="Dlitems" runat="server" RepeatDirection="Horizontal" RepeatColumns="4"
CellPadding="0" CellSpacing="15" OnItemCommand="Dlitems_ItemCommand" 
OnItemDataBound="Dlitems_ItemDataBound">
...

And define it like this

protected void Dlitems_ItemDataBound(Object sender, DataListItemEventArgs e)
{
   if (e.Item.ItemType == ListItemType.Header)
   {
       Label lblCat = (Label)e.Item.FindControl("lblcat");
       lblCat.Text = "Changed!";

    }    
}