Cast from type 'DBNull' to type 'String' is not valid.

I have seen this question many times in the ASP.NET forums and thought that it would be a good idea to blog about.
When you are working with functions in the HTML of your DataGrid and passing the value (which can be also NULL) from the database to a function, which accepts a string, then you will get such an error.

Cast from type 'DBNull' to type 'String' is not valid.

To get this working you will have to pass the value as an object. That means the function must simply accept it as an object instead of a string. Something like this:

<asp:datagrid id="datagrid".....>
<Columns>
<asp:TemplateColumn ...>
  <ItemTemplate>
    <%# DoSomething(Container.DataItem("TheValue")) %>
  </ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid>

And in your Codebehind:

function public DoSomething(Dim obj as Object)
  If not IsDBNull(obj) then
  ' Do the processing here...
  End If
end function


Sonu

Comments

# Jerry Pisk said:

You don't have to pass it as object. Simply use the as operator, like this:

DoSomething(Container.DataItem("TheValue") as string);

and check for null in DoSomething.

Tuesday, December 21, 2004 6:28 PM
# David Silverlight said:

Interesting approach. Thanks for the suggestion. If it works, I might change my approach. I normally handle nulls a bit differently, though, but I might try this approach. I would expect that it would complain if you added "as string" the same way it would if you passed a null value to a string parameter. Sonu, did this do the trick?

Tuesday, December 21, 2004 9:34 PM
# Sonu Kapoor said:

Unfortunaly not David. The approach which Jerry doesnt work for me.

Tuesday, December 21, 2004 9:40 PM
# Sonu Kapoor said:

* which Jerry described...

Tuesday, December 21, 2004 9:40 PM
# Mike said:

Great Tip!!!

Tuesday, December 28, 2004 2:35 PM
# Chris said:

Why not handle the null on in the Database query? This way any controls that use the query are handled...

Thursday, January 13, 2005 12:39 AM
# gridview said:

Jerry your approach doesnt work for me.

Wednesday, June 27, 2007 3:15 AM
# Brendan said:

You could handle the null on the query side by using a case statement in your select statement.  In this manor, if the datum is null, then simply return a more desirable value, such as an empy string.

Monday, July 30, 2007 1:04 PM
# E C said:

Brendan, Could you give an example of how that would look in the query?

Monday, August 13, 2007 4:32 PM
# Nick Corley said:

I ran into a similar problem where the data item was a dbnull and was able to use "as string" like this:

Convert.ToDouble(row["DoubleRow"] as string)

Friday, August 17, 2007 12:30 PM
# WebMonkey-in-Ireland said:

I wish MS had built this in...

txtAddress1.Text = objReader.Item("Address1")

If something like this is NULL it throws an error which is needless. Simply have a property to do a silent conversion to string.

Thursday, December 13, 2007 5:53 AM
# yo said:

Convert.ToString(databaseobject)

Tuesday, May 06, 2008 10:00 AM
# rareddy said:

If you're using a Dataset, just tell the designer to return any NULL values as Empty.

Friday, May 09, 2008 1:28 PM
# SomeOne said:

You can do row["DoubleRow"].ToString() and it will produce String.Empty if the value is DBNull.

Tuesday, March 03, 2009 5:12 PM
# Seppe said:

Dude, thanks a lot, you solved a big headache!!!!

Wednesday, October 28, 2009 3:06 PM
# espn3 ipad app said:

Do what you say,say what you do

-----------------------------------

Saturday, December 18, 2010 4:50 AM
# ipad accessories said:

-----------------------------------------------------------

I used to be extremely delighted to locate this site.I wanted to say thanks to you with regard to this great learn!!! I absolutely loved each and every tiny little bit of it and I've you bookmarked to check out new items you article.

Tuesday, January 04, 2011 2:47 AM
# ipad application said:

-----------------------------------------------------------

"Hello to all I can’t recognize how you can add your site in my rss reader. Enable me, please"

Sunday, January 09, 2011 2:01 AM
# product reviews said:

"Hello, I found your blog in a new directory of blogs. I dont know how your web site arrived up, must happen to be a typo, Your blog seems to be excellent. Have a awesome day."

--------------------------------------------------------------------    

Slavic Languages and Literatures

Saturday, March 12, 2011 7:22 PM
# Home Security Monitoring companies said:

great points altogether, you just gained a brand new reader. What would you recommend about your post that you made some days ago' Any positive'

<b><a href="www.articlecoop.com/.../Suggestions-for-Searching-for-a-Home-Security-Camera.html

">Home Security Monitoring companies

<a/><b/>

Saturday, April 09, 2011 9:24 AM
# Chet Crantz said:

I'm not that a lot of a online reader to be honest but your websites definitely nice, keep it up! I'll go ahead and bookmark your web site to come back later.

Wednesday, June 29, 2011 3:21 PM
# zkutch said:

write new function in sql which examines if value is null, then returned ' '

Monday, July 04, 2011 12:44 PM
# edu backlinks said:

I simply couldn't go away your site before suggesting that I really loved the usual information a person supply to your guests? Is going to be back incessantly to check up on new posts  <a href=edubacklinksstore.com/>edu backlinks</a>

Wednesday, July 27, 2011 5:18 PM
# tryecrot said:

Yes there should realize the opportunity to RSS commentary, quite simply, CMS is another on the blog.

Saturday, August 27, 2011 11:08 PM
# jason said:

how should i get override this error?

Cast from type 'DBNull' to type 'String' is not valid.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Cast from type 'DBNull' to type 'String' is not valid.

Source Error:

Line 506:        For j = 0 To DS_TL.Tables("tmtestlog").Rows.Count - 1

Line 507:              if DS_TL.Tables("tmtestlog").Rows(j).Item("CONFIGUREDTESTCASE").GetType.ToString <> "System.DBNull" Then

Line 508:    if IsDBNull(DS_TL.Tables("tmtestlog").Rows(j).Item("VERDICT")) then

Line 509:                verdict = Convert.ToString(DS_TL.Tables("tmtestlog").Rows(j).Item("VERDICT"))

Line 510: end if

Source File: C:\Inetpub\wwwroot\CQTM4E\Summary_Scurve.aspx.vb    Line: 508

Stack Trace:

[InvalidCastException: Cast from type 'DBNull' to type 'String' is not valid.]

  Microsoft.VisualBasic.CompilerServices.StringType.FromObject(Object Value) +616

  CQTM4E.Summary_Scurve.mycount() in C:\Inetpub\wwwroot\CQTM4E\Summary_Scurve.aspx.vb:508

  CQTM4E.Summary_Scurve.increase(DateTime start, DateTime enddate, Double inc, String IT_ID, Boolean last_iteration) in C:\Inetpub\wwwroot\CQTM4E\Summary_Scurve.aspx.vb:456

  CQTM4E.Summary_Scurve.builddata(String IT_ID) in C:\Inetpub\wwwroot\CQTM4E\Summary_Scurve.aspx.vb:364

  CQTM4E.Summary_Scurve.Page_Load(Object sender, EventArgs e) in C:\Inetpub\wwwroot\CQTM4E\Summary_Scurve.aspx.vb:119

  System.Web.UI.Control.OnLoad(EventArgs e) +67

  System.Web.UI.Control.LoadRecursive() +35

  System.Web.UI.Page.ProcessRequestMain() +750

Could anyone tell me?

Many thanks~

Monday, August 29, 2011 7:53 AM
# Lourenco said:

Hey,

Just found a helpful post. It is basic really.

If your using dataset designer, each field has a Null value handler that can be set to "Empty", "Nothing" or Throw Exception. Usually it is set to "throw exeception, just set it to the one you need to test.

@ forums.asp.net/.../3910599.aspx

Regards,

Thursday, September 15, 2011 12:54 PM
# Jerry said:

ASP.NET Check DBNULL value C# and vb.net fullsource code example

asp.net-informations.com/.../asp-dbnull.htm

Jerry.

Saturday, October 15, 2011 2:52 AM

Leave a Comment

(required) 
(required) 
(optional)
(required)