Unable to cast object of type 'System.DBNull' to type 'System.String'.

Hi i have the following which is meant to check if an image is available and if it isnt it should show a default image however, it gives me this error whenever the image is null in the database.

This is the function which returns the error;

protected string FormatImageUrl(object url)

{

if ((url != DBNull.Value) && (url != null) && (url.ToString().Trim().Length > 0))

{

//if (File.Exists(url))

return (url.ToString().Trim());

}

else

{

return "~/images/default.gif";

}

}

0
Pmillio
5/4/2009 4:33:06 PM
asp.net.getting-started 91979 articles. 4 followers. Follow

15 Replies
1433 Views

Similar Articles

[PageSpeed] 40
Get it on Google Play
Get it on Apple App Store

Hey,

Doesn't seem to pass the dbnull check.  Try to do:  if ((!DBNull.Value.Equals(url)) && ..

Instead.  This works for me for sure.


Brian

"Trust in the Lord and do what is good; dwell in the land and live securely. Take delight in the Lord, and He will give you your heart's desires" (Psalm 37: 3-4).
0
bmains
5/4/2009 4:50:22 PM
Hi Bmains, i tried that and it didnt work either.
0
Pmillio
5/4/2009 4:55:55 PM

Pmillio, try || instead of &&. It seems like you are trying to satisfy "all" condition instead of "any" condition.

0
shahk26
5/4/2009 4:56:17 PM

Hi i tried that as well and it didnt work either, here is how it looks;

protected string FormatImageUrl(object url)

{

if ((!DBNull.Value.Equals(url)) || (url != null) || (url.ToString().Trim().Length > 0))

{

//if (File.Exists(url))

return (url.ToString().Trim());

}

else

{

return "~/images/default.gif";

}

}

0
Pmillio
5/4/2009 5:09:29 PM

What is Url object? It's just a string? Is there any specific reasons that you want to check with dbnull? DBNull is to check the whether the data in the specific column is null or not. If url is just a string then you can check for not null or length > 0. You do not need to check for dbnull. Let's try and see what happens.

if (!String.IsnullorEmpty(url))

{

retrurn url;

}

else

......

 

0
shahk26
5/4/2009 5:30:20 PM

you can not equal a value with DBNULL ...

try this instead, it will wrok

 

1        Public Function CheckMyValue(ByVal val As Object) As String
2            If val.GetType Is DBNull.Value.GetType Then
3                Return "this data is null"
4    
5            Else
6    
7                ' do your rest code
8                Return "Something"
9    
10           End If
11   
12       End Function
13   
  
Plz remember to click "Mark as Answer" if this helped you.

Abdulla AbdelHaq    MCTS, MCPD
"Experience is simply the name we give our mistakes"
0
Abdulla
5/4/2009 5:33:31 PM

Try this:

protected string FormatImageUrl(object url)
{
 if ((url != DBNull.Value))  
{
  if(url.ToString().Trim().Length > 0))
     return (url.ToString().Trim());
}
else
{

    return "~/images/default.gif";

 }

}


Please mark it as answer if it resolves the issue.

visit: http://technicalsol.blogspot.com
0
sumitd
5/4/2009 5:37:16 PM

Try


if ((url != null) && (!url.Equals(DBNull.Value)) && (url.ToString().Trim().Length > 0))

0
mchaitan
5/4/2009 5:48:57 PM

Hi sumitd and it gives me an error messages saying not all code paths return a value.

I have also tried everyhting else and it doesnt work either, this is what my html side looks like just incase it may help;

<asp:Image ID="imgArticle" Width="50px" Height="50px" ImageUrl='<%# (string) FormatImageUrl((string) Eval("ArticlePic")) %>'

0
Pmillio
5/4/2009 5:51:06 PM

try this

protected string FormatImageUrl(object url)

{

if ((url != String.Empty) && (url != null))

{

//if (File.Exists(url))return (url.ToString().Trim());

}

else

{

return "~/images/default.gif";

}

}

 


MAKMark as Answer if this reply helps you
MVP ASP/ASP.Net
MVP ASP/ASP.Net
ASP.Net Hosting : Host DepotMy Site : ASPSnippets
0
mudassarkhan
5/4/2009 5:53:16 PM

 

1    <asp:Image ID="imgArticle" Width="50px" 
2 Height="50px"
3 ImageUrl='<%# FormatImageUrl(Eval("ArticlePic")) %>' />
 
1            Public Function CheckMyValue(ByVal val As Object) As String
2 If
Not val.GetType Is DBNull.Value.GetType Then
3
4 If Not String
.IsNullOrEmpty(val ) Then
5 Rertun Val.ToString.Trim
6 End If
7 End If
8
9 Return
'Your Default Image Here'
10
11 End Function
12
 
Or just simply use RowDataBound Event, you can access the image control and do what ever you want in there .

Plz remember to click "Mark as Answer" if this helped you.

Abdulla AbdelHaq    MCTS, MCPD
"Experience is simply the name we give our mistakes"
0
Abdulla
5/4/2009 6:08:58 PM

Hi that didnt work either, this was my code;

if ((url.ToString() != String.Empty) && (url.ToString() != null))

{

//if (File.Exists(url))

return (url.ToString().Trim());

}

0
Pmillio
5/4/2009 6:10:14 PM

Did you try -

 if ((url != null) && (!url.Equals(DBNull.Value)) && (url.ToString().Trim().Length > 0))

This should work. 

 

0
mchaitan
5/4/2009 6:13:11 PM

 Can you do

Response.Write(url);

I just wanted to check whats the value of the utl being passed.

Or if you can put a breakpoint and debug to see the value of URL in the immediate window.


Thanks,
Karan

~ Remember To Mark The Post(s) That Helped You As The ANSWER ~
0
karan
5/4/2009 6:37:41 PM

Hi Guys, thanks for all your help, i have finally solved it,

i changed this;

<asp:Image ID="imgArticle" Width="50px" Height="50px" ImageUrl='<%# (string) FormatImageUrl((string) Eval("ArticlePic")) %>'

to this, and it works;

<asp:Image ID="imgArticle" Width="50px" Height="50px" ImageUrl='<%# (object) FormatImageUrl((object) Eval("ArticlePic")) %>'

 If anyone can forsee any problems please let me know. Thanks once again

0
Pmillio
5/4/2009 6:45:37 PM
Reply:

Similar Artilces:

System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'
Hello , I am a data table with null able Columns.I am not able to catch the value for DBNull. I did set a value to be returned as empty in dataset. Here is the code where i am trying to catch.1 public List GetStores() 2 { 3 List tmpStore = new List(); 4 StoresService.shopDBDataSet.StoresDataTable stores = 5 storesService.GetStores(); 6 for (int i = 0; i < stores.Count ; i++) 7 { 8 Store store = new Store(); 9 store.StoreID = stores[i].StoreID...

How do I get around this error "Unable to cast object of type 'System.DBNull' to type 'System.String' "
I am using Visual Developer 2008 Express Edition for the first time, and I keep getting the following error below. The site allows anyone to enter with a valid username and password, but even when I logoff the site I get the same error....like the memory or database is not getting refreshed. I would think that when I initially compile the site that anything left in memory would be flushed out. Can someone please help me to figure this out. Thanks,Ramell P.S. The site is programmed using C#    Unable to cast object of type 'System.DBNull' to type 'System.String&...

Unable to cast object of type 'System.DBNull' to type 'System.String'
I have received the following error when I am logged in as administrator.  I wanted to test the load event feature.  Allows me to load and save new event.  I can view event on location view page but when I try to link to "list or calender" view I receive this error "Unable to cast object of type 'System.DBNull' to type 'System.String'.  Debug highlights the <asp:HyperlinkID as errored line. Any assistance would be greatly appreciated Brian   <DayEventTemplate> <div style="padding: 3px;"> <asp:Hyper...

Unable to cast object of type 'System.DBNull' to type 'System.String'. #2
I am getting this error when I try to run the code below. The error is happening on the last for each loop || foreach (string s in dr.ItemArray) || Please see below:        private void button1_Click(object sender, EventArgs e)        {            string myOutput = "";            DataTable dt = new DataTable();            using (TextReader tr = File.O...

Eventcalender: Unable to cast object of type 'System.DBNull' to type 'System.String'.
 I added an event in the eventcalender. When I try to view the events_calender.aspx I get this error message, what can be wrong??   Server Error in '/bfc_csk' Application. Unable to cast object of type 'System.DBNull' to type 'System.String'. 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: Unable to cast object of type 'System.DBNull' to type 'System.String'.Source Err...

Unable to cast object of type 'System.DBNull' to type 'System.String'. #2
 Hi:I am totally new to asp.net and downloaded the club website project. I have not done anything to the events page yet but as soon as i tried to add an event I got the following error. "Unable to cast object of type 'System.DBNull' to type 'System.String'." Can someone help me out here?ThanksBrian  This bug has been covered in the Identified Bugs and fixes section.  http://forums.asp.net/t/970081.aspx There are a few solutions and discussions on fixes, you will need to read through it to find the fix. Support@aspsksolutions.com Without kno...

System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Byte[]'.
Hi All, I am trying to retrieve a Picture from an SQL 2005 database. Here is my code:Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim ListingID As String = (Request.QueryString("GUID")) 'Connect to the database and bring back the image contents & MIME type for the specified pictureUsing myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionStringListings").ConnectionString) Const SQL As String = "SELECT [Pic1Ext], [Picture1] FROM [Listings] WHERE [ListingID] = @ListingID"C...

"Unable to cast object of type 'System.String' to type 'System.String[]'."
hi i'm using the following statement in my applicationstring[] strTArray = new string[5]; strTArray = (string[])(Session["TextDataArray"]); when i run the application its giving the below error {"Unable to cast object of type 'System.String' to type 'System.String[]'."} can anyone say how to solve this thanks in advance Archu What are you storing in the TextDataArray session? What is the data type you are storing?   RegardsBilal Hadiar, MCP, MCTS, MCPD, MCTMicrosoft MVP - Telerik MVP...

Unable to cast object of type '<>f__AnonymousType1`3[System.Guid,System.String,System.String]' to type 'aspnet_User'.???
Hi everyone, What does this error mean?  ERROR: Unable to cast object of type '<>f__AnonymousType1`3[System.Guid,System.String,System.String]' to type 'aspnet_User'. Thank's a lot /PepePepe JoseNewbie@C#.Net&jRuby What type is in your DataItem?  A Guid? or a String?  Either way, it's telling you cant cast it to a aspnet_User type.  Let us know what your DataItem is and we can help further.Good Luck and happy programming!Let's build community! If my post helped you, mark it as the Answer and I will do the same when you help me.....

Unable to cast object of type 'System.String[]' to type 'System.IConvertible'.
hi expert   i try get the string from request.querystring("CID") from the error messege i know that is string[] (array) how to convert it to int32 and request.querystring("CID") is int value   Line 19: protected void ObjectDataSourceCarPicture_Inserting(object sender, ObjectDataSourceMethodEventArgs e) Line 20: { Line 21: e.InputParameters.Add("CID", Convert.ToInt32(Request.QueryString.GetValues("CID")) ); Line 22: // e.InputParameters.Add("CID", Convert.ToInt32( Convert.ToString( a Request.QueryString.GetValues("CID"))))); Line 23: ...

Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.
I'm getting Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'. anyone knows how to write some code to check if my binary data is null then continue check another data? I've tried but seems that byte and string can't convert...  (hope someone can provide me code in VB and where to insert them :))  Here's my code:Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim ID As Integer = Convert.ToInt32(Request.QueryString("ID"))Using myConnection As New SqlConnection(Configuratio...

Web resources about - Unable to cast object of type 'System.DBNull' to type 'System.String'. - asp.net.getting-started

Resources last updated: 1/11/2016 9:08:52 PM