2008-12-23 46 views
0

我有一箇中繼器,只有存在時才顯示綁定字段值。讀了this post我決定通過在我的轉發器中使用一個字面值並使用OnItemDatabound觸發器來填充我的字面值,但我的字面值似乎無法從後面的c#代碼訪問,我不明白爲什麼!空字面問題

繼承人的aspx頁面

<asp:Repeater runat="server" ID="rpt_villaresults" OnItemDataBound="checkForChildren"> 
    <HeaderTemplate> 

    </HeaderTemplate> 
    <ItemTemplate>  
//.................MORE CODE HERE......................       
<div class="sleeps"><h4>To Sleep</h4><h5><%#Eval("sleeps")%> <asp:Literal ID="sleepsChildrenLit" runat="server" /> </h5></div> 
//.............MORE CODE HERE........................ 

背後

public void checkForChildren(object sender, RepeaterItemEventArgs e) 
{ 
    Literal childLit = e.Item.FindControl("sleepsChildrenLit") as Literal; 
    //this is null at runtime 
    String str = e.Item.DataItem.ToString(); 
    if (e.Item.DataItem != null) 
    { 
     if (Regex.IsMatch(str, "[^0-9]")) 
     { 
      if (Convert.ToInt32(str) > 0) 
      { 
       childLit.Text = " + " + str; 
      } 
     }   
    } 
} 

回答

2

正如你時,你說可能知道代碼:as Literal它可以返回null值。如果你做了適當的轉換,你會在運行時得到一個異常,它會給你更多的信息,告訴你什麼是錯誤的和/或哪個元素導致你的問題。

如果你總是期望「chilLit」有一個值,你不檢查空值,那麼你應該使用

Literal childLit = (Literal)e.Item.FindControl("sleepsChildrenLit"); 
+0

英雄所見略同;) – 2008-12-23 11:21:21

2

那麼,與當前的代碼,我們不知道這是否是其轉換爲文字因爲e.Item.FindControl返回null,或者因爲它不是Literal。這就是爲什麼你應該使用轉換而不是「as」,如果你確信它確實應該是這種類型的話。

更改代碼:

Literal childLit = (Literal) e.Item.FindControl("sleepsChildrenLit"); 

,看看會發生什麼。如果你得到一個轉換異常,你會知道這是因爲它是錯誤的類型。如果你仍然得到一個NRE,那麼FindControl返回null。

編輯:現在,除此之外,讓我們來看看代碼後:

String str = e.Item.DataItem.ToString(); 
if (e.Item.DataItem != null) 
{ 
    ... 
} 

如果e.item.DataItem爲null,則調用toString()方法會拋出異常 - 這樣的檢查在下一行是毫無意義的。我懷疑你實際上想:

if (e.Item.DataItem != null) 
{ 
    String str = e.Item.DataItem.ToString(); 
    ... 
} 
+0

謝謝喬恩。我使用了演員,並且childLit仍然爲空。 也很奇怪,intelisense沒有在後面的代碼中提取文字。我應該能夠引用sleepsChildrenLit.Text ....但我不能即使它在服務器上運行。 我以爲你可以把文字放在任何地方? – mancmanomyst 2008-12-23 11:28:28

2

的OnItemDataBound事件處理checkForChildren()也將要求中繼器的HeaderItem。 但在這種情況下,e.Item.DataItem將爲空。當然,FindControl()也會返回null,因爲在HeaderTemplate中你沒有一個ID爲「sleepsChildrenLit」的Literal控件。

可以使用e.Item.ItemType屬性來檢查當前項目是否是FooterItem的HeaderItem,或「正常」的項目,如:

if (e.Item.ItemType == ListItemType.Header) 
{ 
... 
} 
else if (...) 
{ 
... 
}