2017-10-15 57 views
0

我試圖訪問嵌套在DataList ItemTemplate中的控件。對於我的生活,我無法理解我做錯了什麼。舉個例子:如何訪問嵌套在DataList中的ASP控件項目模板

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 

    <!DOCTYPE html> 

    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <head runat="server"> 
     <title></title> 
    </head> 
    <body> 
     <form id="form1" runat="server"> 
      <div> 
      </div> 
      <asp:DataList ID="DataList1" runat="server"> 
       <ItemTemplate> 
        <asp:Label ID="lblSavings" runat="server" Text="Label"></asp:Label> 
       </ItemTemplate> 
      </asp:DataList> 
     </form> 
    </body> 
    </html> 

在後面的代碼我試圖訪問「lblSavings」的標籤控制,例如:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

public partial class _Default : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     lblSavings.Text = "String"; 
    } 
} 

這就像後面的代碼無法看到,控制什麼的。我錯過了某個步驟,還是我瘋了?

謝謝大家!

+0

是一個編譯錯誤?我會嘗試在datalist的'itemDataBound'事件中設置它的值... –

回答

0
Hope this will help you. 
Feel free to ask if got any query. 

protected void Page_Load(object sender, EventArgs e) 
{ 
      Label lbl = Datalist1.Item.FindControl("lblSavings") as Label; 
} 

or at time of item bound 

protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs 
e) 
{ 
Label Label1 = e.Item.FindControl("lblSavings") as Label; 
} 
相關問題