【问题标题】:accessing controls in datalist headertemplate from codebehind从代码隐藏访问 datalist headertemplate 中的控件
【发布时间】:2016-10-26 02:10:11
【问题描述】:

我的应用程序中有一个数据列表,其 headertemplate 有一个标签。现在我需要从代码隐藏访问标签。我该怎么做..

代码

      <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>

注意:我需要从 headertemplate 访问标签lblcat..

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    像这样用你的数据列表附加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!";
    
        }    
    }
    

    【讨论】:

    • 对于将绑定到列表的每个项目,但它只会进入 if 条件一次,因为 ItemType 标头只出现一次
    • 我在这里没有绑定任何东西。我只是想根据某些条件将文本提供给代码隐藏中的标签......
    • 如果你没有将任何东西与你的数据列表绑定,那么你在其中显示的内容,数据列表需要什么?
    • 那叫你绑定你的数据列表。您必须调用 DlistItems.Datasource=... 和 DlistItems.Databind();方法,即数据绑定。我认为你还没有完成作业,也没有尝试过任何事情
    【解决方案2】:

    上面的代码是正确的,但是您需要将帖子添加回代码并正确定义它,因为用户没有点击任何按钮或链接,所以我们不想显示 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;
        }
       }
    

    快乐编程

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多