2008-12-23 53 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 (...) 
{ 
... 
}