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..
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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!";
}
}
Method 2
The above code is correct however you will need to add post back to the code and define it correctly as the user has not click on any buttons or links so we do not want to display Changed unless the user click on the link or button. The as following does that:
protected void dlData_ItemDataBound(object sender, DataListItemEventArgs e)
{
try
{
if (Page.IsPostBack)
{
if (e.Item.ItemType == ListItemType.Header)
{
Label lblCat = (Label)e.Item.FindControl("lblcat");
lblCat.Text = "Changed!";
}
}
}
catch (Exception ex)
{
throw;
}
}
Happy Programming
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0