简体   繁体   中英

Object not set to an instance of an object

I've been scratching my head about this for about a day now and need some help. I have a GridView and I would like to change the back-color of the row based on a database field. The db field is "Inactive".

Here is the markup:

<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>

Here is the code:

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")
       {
       }
    }
}

I get an error:

Object reference not set to an instance of an object."

an the line

if (hf.Value == "True")

Anyone have any ideas on why this is happening?

There is mismatch between HiddenField's Id in markup and in code. Use this:

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

In common case, to prevent NullReferenceException, check against 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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM