对象未设置为对象的实例

本文关键字:对象 实例 设置 | 更新日期: 2023-09-27 18:12:44

我已经为这个问题挠头一天了,需要一些帮助。我有一个GridView,我想改变基于数据库字段行的背景颜色。db字段为"Inactive"

标记如下:

<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")
有人知道为什么会发生这种情况吗?

对象未设置为对象的实例

标记和代码中HiddenField的Id不匹配。使用:

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

一般情况下,为了防止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");
}