accessing controls in datalist headertemplate from codebehind

前端 未结 2 1990
清歌不尽
清歌不尽 2021-01-26 15:28

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:

         


        
相关标签:
2条回答
  • 2021-01-26 15:41

    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!";
    
        }    
    }
    
    0 讨论(0)
  • 2021-01-26 15:58

    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

    0 讨论(0)
提交回复
热议问题