簡體   English   中英

從代碼背后訪問數據列表標題模板中的控件

[英]accessing controls in datalist headertemplate from 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從HeaderTemplate中..

像這樣將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!";

    }    
}

上面的代碼是正確的,但是由於用戶沒有單擊任何按鈕或鏈接,因此您需要添加回發代碼並正確定義它,因此除非用戶單擊鏈接或按鈕,否則我們不希望顯示已更改。 如下所示:

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

快樂編程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM