Converting a DBNull to boolean when binding to checkbox in a detailsview control

gsirianni picture gsirianni · Dec 7, 2011 · Viewed 12.7k times · Source

This is kind of silly but I have a DetailsView that binds to a record in my database using a sqlDataSource. My problem is that the field I'm binding to is a bit field, (i,e 1 or 0) that at present allows nulls. I realize this needs to change but I also need to be able to handle DBNulls on the GUI side so that the application automatically knows to set the Checked property of the checkbox to "false" if the value is DBNull. At present my template field looks like this.

 </asp:TemplateField>
   <asp:TemplateField HeaderText="Car:" HeaderStyle-Width="15%" ItemStyle-Width="85%">
  <ItemTemplate>
    <asp:Label ID="lblIsCar" runat="server" Text='<%#  Eval("isCar") %>' />
  </ItemTemplate>
  <EditItemTemplate>
    <asp:CheckBox ID="ckIsCar" runat="server"  Checked='<%#  Convert.ToBoolean(Eval("isCar"))%>' />
  </EditItemTemplate>
</asp:TemplateField>

Everything works fine in View mode but when I click the Edit link on the details view control I get the following error:

Object cannot be cast from DBNull to other types.

Any suggestions?

Update:

I need to use 2 way binding through Bind() instead of Eval() as the details view performs an update to the selected record. If i use Convert.ToBoolean() with Bind an exception will be cast. I may end up using a CheckboxField. One would think that there would be an easy way to handle this but I have been unlucky inf finding one.

Answer

Jeff Ogata picture Jeff Ogata · Dec 7, 2011

You could try a conditional to check for DBNull.Value:

Eval("isCar") == DBNull.Value ? false : Convert.ToBoolean(Eval("isCar"))