对象未设置为对象的实例

时间:2011-10-28 14:45:22

标签: c# asp.net .net gridview exception-handling

我现在已经开始关注这个问题大约一天了,需要一些帮助。我有一个GridView,我想根据数据库字段更改行的背景颜色。 db字段为“非活动”。

这是标记:

<asp:GridView ID="GridView1" runat="server" DataSourceID="WishListDS"  AutoGenerateColumns="false" CssClass="WishListGridView" GridLines="None" OnRowDataBound="WishListGV_RowDataBound">
    <Columns>       
        <asp:TemplateField>
            <ItemTemplate>
                <div class="wlMessage">
                    <asp:Hyperlink ID="ViewHL" runat="server" Text="View" NavigateUrl='<%# "WishListSearchResults.aspx?id=" + Eval("sysid")%>' />
                    <asp:Hyperlink ID="EditHL" runat="server" Text="Edit" NavigateUrl='<%# "WishListEdit.aspx?id=" + Eval("sysid")%>' />
                </div>
                <asp:Hyperlink ID="NameLBL" Runat="server" Text='<%# Eval("customName")%>' NavigateUrl='<%# "WishListSearchResults.aspx?id=" + Eval("sysid")%>' CssClass="wlGVContentTitle" />
                <asp:Label ID="ArrivalLBL" Runat="server" Text='<%# Eval("earliestArrival","{0:d}") + " - " + Eval("latestArrival","{0:d}")%>' CssClass="wlGVContent" />
                <asp:Label ID="StateLBL" Runat="server" Text='<%# Eval("City") + ", " + Eval("State")%>' CssClass="wlGVContent"></asp:Label>
                <asp:HiddenField ID="InactiveHF" runat="server" value='<%# Eval("InActive") %>' />
                <hr />               
            </ItemTemplate>
        </asp:TemplateField>             
    </Columns>
</asp:GridView>

以下是代码:

protected void WishListGV_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
       HiddenField hf = (HiddenField)e.Row.FindControl("InActiveHF");
       if (hf.Value == "True")
       {
       }
    }
}

我收到错误:

  

对象引用未设置为对象的实例。“

一行

if (hf.Value == "True")

任何人对于为什么会这样做有任何想法?

2 个答案:

答案 0 :(得分:5)

标记中的HiddenField标识与代码之间存在不匹配。使用此:

HiddenField hf = (HiddenField)e.Row.FindControl("InactiveHF");

答案 1 :(得分:2)

通常情况下,要防止NullReferenceException,请检查null:

HiddenField hf = (HiddenField)e.Row.FindControl("id");
if (hf != null && hf.Value == Boolean.TrueString)
{
}
else
{
    // handle on your own, e.g.:
    throw new InvalidOperationException("Control not found");
}