空文字问题

时间:2008-12-23 11:09:01

标签: c# asp.net casting literals

我有一个转发器,只有在存在时才应显示绑定字段值。阅读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;
            }
        }         
    }
}

3 个答案:

答案 0 :(得分:2)

正如您可能知道的那样:as Literal它可以返回null个值。如果你进行了适当的强制转换,你将在运行时获得一个异常,它将为你提供更多关于错误和/或导致问题的元素的信息。

如果你总是希望“chilLit”有一个值并且你没有检查空值那么你应该使用

将其转换为Literal
Literal childLit = (Literal)e.Item.FindControl("sleepsChildrenLit");

答案 1 :(得分: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();
    ...
}

答案 2 :(得分:2)

还将为转发器的HeaderItem调用OnItemDataBound事件处理程序checkForChildren()。 但在这种情况下,e.Item.DataItem将为null。当然,FindControl()也将返回null,因为你没有HeaderTemplate中带有ID“sleepsChildrenLit”的Literal控件。

您可以使用e.Item.ItemType属性检查当前Item是FooterItem的HeaderItem还是“normal”Item,例如:

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