从codebehind访问数据列表头模板中的控件
本文关键字:控件 表头 codebehind 访问 数据 列表 | 更新日期: 2023-09-27 17:59:46
我的应用程序中有一个数据列表,它的头模板有一个标签。现在我需要从codebehind访问标签。我怎么能那样做。。
代码:
<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>
注意:我需要从头模板访问标签lblcat
。。
将OnItemDataBound
事件附加到您的数据列表中,如
<asp:DataList ID="Dlitems" runat="server" RepeatDirection="Horizontal" RepeatColumns="4"
CellPadding="0" CellSpacing="15" OnItemCommand="Dlitems_ItemCommand"
OnItemDataBound="Dlitems_ItemDataBound">
...
并像这个一样定义它
protected void Dlitems_ItemDataBound(Object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
Label lblCat = (Label)e.Item.FindControl("lblcat");
lblCat.Text = "Changed!";
}
}
上面的代码是正确的,但是您需要将post添加回代码中并正确定义它,因为用户没有点击任何按钮或链接,所以除非用户点击链接或按钮,否则我们不希望显示Changed。如下所示:
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;
}
}
快乐编程