Reputation: 115
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?
Upvotes: 1
Views: 1766
Reputation: 100268
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");
}
Upvotes: 2
Reputation: 22448
There is mismatch between HiddenField's Id in markup and in code. Use this:
HiddenField hf = (HiddenField)e.Row.FindControl("InactiveHF");
Upvotes: 5