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

Hi i get the following error, Unable to cast object of type 'System.DBNull' to type 'System.String'.  A generic image is meant to appear when no image is found in the database for a particular product, this is how the code is laid out;

protected string FormatImageUrl(string url)

{

if (url != null && url.Length > 0)

{

//if (File.Exists(url))

return (url);

}

else

{

return "~/Images/CompanyProducts/No_image.jpg";

}

}

 

And the html is like this;

<asp:Image ID="Image1" ImageUrl='<%# (string) FormatImageUrl( (string) Eval("productImage")) %>' runat="server" />

 

How can i resolve the error, thank you.

0
Pmillio
7/18/2008 1:21:01 PM
asp.net.web-forms 93655 articles. 6 followers. Follow

9 Replies
1450 Views

Similar Articles

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

Change your ASP tag to be: 

<asp:Image ID="Image1" ImageUrl='<%# FormatImageUrl(Eval("ProductImage")) %>' runat="server" />

 Then change your method to be: 

protected string FormatImageUrl(object url) 
{
    if (url != DBNull.Value) 
    {
        return url; 
    }
    else
    {
        return "~/Images/CompanyProducts/No_image.jpg"; 
    }
}
 
0
MelvynHarbour
7/18/2008 1:42:15 PM

 change the method as follow

  protected string FormatImageUrl(object url)
        {

            if (url != null && url.ToString().Length > 0)
            {

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

            }

            else
            {
                return "~/Images/CompanyProducts/No_image.jpg";

            }

        }

and html as 

<asp:Image ID="Image1" ImageUrl='<%# FormatImageUrl(Eval("productImage")) %>' runat="server" />


Jeev
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you get the answer to your question, please mark it as the answer.
0
Jeev
7/18/2008 1:43:29 PM

 Try this:
  

protected string FormatImageUrl(object urlObj)
{
   string url;

   if (urlObj != null)
   {
      url = (string)urlObj;
      if (url.Length > 0 && File.Exists(url))
         return (url);
   }

   return "~/Images/CompanyProducts/No_image.jpg";
}

<asp:Image ID="Image1" ImageUrl='<%# FormatImageUrl(Eval("productImage")) %>' runat="server" />

if (this.IsHelpful) this.MarkAsAnswer();
0
Trax72
7/18/2008 1:44:44 PM

Hi MelvynHarbour i tried your solution and i got thsi error Compiler Error Message: CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)

 

0
Pmillio
7/18/2008 2:32:32 PM

Thanks guys for all your help i used Jeev's solution and it worked perfect.

0
Pmillio
7/18/2008 2:34:57 PM

 Pmillio try out my code snippet and see how it goes


Jeev
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you get the answer to your question, please mark it as the answer.
0
Jeev
7/18/2008 2:35:41 PM

My mistake, I needed to cast the url object as a string explicitly.

Note that Jeev's solution won't work quite right I think - DBNull.Value is not the same as null and the evaluation won't work correctly.

0
MelvynHarbour
7/18/2008 2:38:55 PM
Hi i used jeevs solution and so far it is working.
0
Pmillio
7/18/2008 2:40:29 PM

MelvynHarbour:
Note that Jeev's solution won't work quite right I think - DBNull.Value is not the same as null and the evaluation won't work correctly.
   Well that is taken care of by doing the .ToString()  If you do a .Tostring() on a dbnull it returns an empty string


Jeev
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you get the answer to your question, please mark it as the answer.
0
Jeev
7/18/2008 2:42:08 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...

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...

Unable to cast object of type 'System.String' to type 'System.Web.UI.WebControls.Parameter'.
I'm getting this error on a vb.net page the needs to execute two separate stored procedures.  The first one, is the main insert, and returns the identity value for the ClientID.  The second stored procedure inserts data, but needs to insert the ClientID returned in the first stored procedure.  What am I doing wrong with including the identity value "ClientID" in the second stored procedure?  Unable to cast object of type 'System.String' to type 'System.Web.UI.WebControls.Parameter'. Description: An unhandled exception occurred during t...

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.....

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.DateTime' to type 'System.String'.
 Hi,      I got this field (dateSubmitted) having a data type of DateTime but I receive this error "Unable to cast object of type 'System.DateTime' to type 'System.String'."       All value for dateSubmitted field are 12/27/2007 12:00:00 AM. cheers,imperialx  imperialx:I got this field (dateSubmitted) having a data type of DateTime but I receive this error "Unable to cast object of type 'System.DateTime' to type 'System.String'." Can you explain it further as to, ...

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

Resources last updated: 11/23/2015 8:18:15 PM