2010-05-29 60 views
0

在我的.aspx頁面中我有我的DataList:如何找到DataList控件中的一個標籤,它被設置爲True

<asp:DataList ID="DataList1" runat="server" DataKeyField="ProductSID" 
    DataSourceID="SqlDataSource1" onitemcreated="DataList1_ItemCreated" 
    RepeatColumns="3" RepeatDirection="Horizontal" Width="1112px"> 
    <ItemTemplate> 
     ProductSID: 
     <asp:Label ID="ProductSIDLabel" runat="server" Text='<%# Eval("ProductSID") %>' /> 
     <br /> 
     ProductSKU: 
     <asp:Label ID="ProductSKULabel" runat="server" Text='<%# Eval("ProductSKU") %>' /> 
     <br /> 
     ProductImage1: 
     <asp:Label ID="ProductImage1Label" runat="server" Text='<%# Eval("ProductImage1") %>' /> 
     <br /> 
     ShowLive: 
     <asp:Label ID="ShowLiveLabel" runat="server" Text='<%# Eval("ShowLive") %>' /> 
     <br /> 
     CollectionTypeID: 
     <asp:Label ID="CollectionTypeIDLabel" runat="server" Text='<%# Eval("CollectionTypeID") %>' /> 
     <br /> 
     CollectionHomePage: 
     <asp:Label ID="CollectionHomePageLabel" runat="server" Text='<%# Eval("CollectionHomePage") %>' /> 
     <br /> 
     <br /> 
    </ItemTemplate> 
</asp:DataList> 

而在背後使用ItemCreated事件我的代碼找到並設置label.backcolor屬性。 (注:我使用的是遞歸的FindControl類

protected void DataList1_ItemCreated(object sender, DataListItemEventArgs e) 
    { 

     foreach (DataListItem item in DataList1.Items) 
     { 
      if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
      { 
      Label itemLabel = form1.FindControlR("CollectionHomePageLabel") as Label; 
      if (itemLabel !=null || itemLabel.Text == "True") 
      { 
       itemLabel.BackColor = System.Drawing.Color.Yellow; 
      } 
    } 

當我運行該頁面時,itemLabel被找到,並且顏色顯示。但它將itemLabel顏色設置爲在DataList中找到的itemLabel的第一個實例。在DataList中的所有itemLabel中,只有一個將text = True - 並且應該是拾取背景色的標籤。另外:itemLabel正在拾取名爲「CollectionHomePage」的True/False位數據類型的數據庫中的一列。我必須缺少一些簡單的...謝謝你的想法。

回答

1

ItemCreated事件是爲每個數據列表項執行的,它不是全局的,所以你爲每個項目執行相同的代碼,恐怕對你的情況這是錯誤的。

您只需檢查當前創建的項目。此外,由於對項目產生的數據還沒有被綁定到項目,你需要使用ItemDataBound事件

在這裏,您有可能會爲你

protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e) 
{ 
    foreach(Control control in e.Item.Controls) 
    { 
     if (control is Label && (control as Label).Text.Equals("True")) 
     { 
      (control as Label).BackColor = System.Drawing.Color.Yellow; 
     } 
    } 
} 
+0

嘿克勞迪奧,它仍然無法正常工作工作的一個片段。當我嘗試了你的建議,頁面加載沒有錯誤,但文本設置爲True的標籤沒有顯示背景顏色。謝謝。 – Doug 2010-05-29 19:06:02

+0

@Doug。請嘗試在事件OnItemDataBound上執行相同的代碼 – 2010-05-29 21:04:35

+0

YES!現在它正在工作。應該首先使用OnItemDataBound。謝謝克勞迪奧。 – Doug 2010-05-29 21:15:40

相關問題