Convert 'System.DBNull' to type 'System.String' ?

I have a textbox on my site that I want to populate with some data, however when the value is null, which is quite often.

The problem is that when I call a static method which returns a string; when that string is DBNull, I get the following error which is absolutely correct.
Unable to cast object of type 'System.DBNull' to type 'System.String'.

So, what should I do to be able to ignore that the string is null and just display a "" string in the texbox?

The code is as follows:

    private void GetCartSmall(string sSessionID)
    {
        Cart2 c = (Cart2)WrapFactory.Create(typeof(Cart2));
        SqlConnection conn = new SqlConnection(db.strConn);
        c.Connection = conn;
        lblBasket.Text = Convert.ToString(c.spCartListSmall(Session.SessionID));
    }


Best regards,
Peter Larsson!


0
PeterLarsson
5/18/2006 8:50:20 AM
asp.net.getting-started 91979 articles. 4 followers. Follow

13 Replies
1335 Views

Similar Articles

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

I can see that you are using a Session. So you need to have this kind of checking before using the Session:

 

if (Session["id"] != null)
{
  if (!Session["id"].ToString().Equals(""))
  {
    // Your code goes here!
  }
}

 

Hope this helps,

Regards


Bilal Hadiar, MCP, MCTS, MCPD, MCT
Microsoft MVP - Telerik MVP
0
haidar_bilal
5/18/2006 10:39:56 AM

the next function returns "" if the value is null. (it's VB, If I remember correctly you need to use the visualbasic namespace for this in C#)

Trim("" & value)

greets,

interw


see my blog at www.Interdevelopments.com and check the future of open mobile widget solutions at www.glowe.org
0
interwanderer1
5/18/2006 10:44:22 AM
Well, the problem is not the session, it has always a value, the problem is when the method returns a DBNull value, as the textbox only accepts a string for it's text.

The question is really, how do I check that my result is not DBNull?

Thanks in advance,
Peter Larsson!

0
PeterLarsson
5/18/2006 11:23:31 AM

 

Look at my previous post.

It's a very usefull function that I use a lot.


see my blog at www.Interdevelopments.com and check the future of open mobile widget solutions at www.glowe.org
0
interwanderer1
5/18/2006 12:36:58 PM
I'm not really quite sure I follow, and I cannot test it right now as I'm at home.

You mean something like this?

string sResult;
if(sResult.Trim("" + c.spCartListSmall(Convert.ToString(sSessionID))
{
    ...
}


If not, could you give me a more code-like example?

/Regards,
Peter Larsson
0
PeterLarsson
5/18/2006 12:56:40 PM

 

I'll give you a visual basic example. up to you to transform it to C#

dim sResult as string
txtMyTextbox.Text = Trim("" & WhateverStringorDatabasevalueYouwant)


see my blog at www.Interdevelopments.com and check the future of open mobile widget solutions at www.glowe.org
0
interwanderer1
5/18/2006 1:27:45 PM

 

litle mistake there...

in the above text your value is in the     "whateverstringordatabasevalueyouwant" string...

you don't need the "sResult" string


see my blog at www.Interdevelopments.com and check the future of open mobile widget solutions at www.glowe.org
0
interwanderer1
5/18/2006 1:29:22 PM

c.spCartListSmall(Session.SessionID) this returns object?

If so:

object obj;

if((obj = c.spCartListSmall(Session.SessionID)) == DBNull.Value)

 lblBasket.Text = String.Empty;

else

 lblBasket.Text = Convert.ToString(obj);

0
rumbafum
5/18/2006 2:08:07 PM
The method returns a string :(

But I think I've found a solution:

try
{
    lblBasket.Text = c.spCartListSmall(Session.SessionID);
}
catch
{
    lblBasket.Text = "";
}

This should do the trick I think.... Will try it later tonight!

Regards,
Peter Larsson

0
PeterLarsson
5/19/2006 1:48:53 PM

If your method returns string and you have a null reference... Is there something wrong in the method, or maybe you can put it returning String.Empty

0
rumbafum
5/19/2006 6:39:00 PM

string textValue = string.Empty;
object sessionObject = c.spCartListSmall(Session.SessionID);

if ( (sessionObject != DBNull.Value) && (sessionObject != null) && (sessionObject.ToString().Trim().Length > 0) )
 textValue = sessionObject.ToString().Trim();

lblBasket.Text = textValue;

NC...

0
NC01
5/19/2006 6:48:18 PM
Thanks for all replies, the solution from 
										NC01 is pretty clever, I'll use that one. :)

Regards,
Peter Larsson!
0
PeterLarsson
5/22/2006 7:07:27 PM

Just keep the tests in the same order as you need to check for null before you do a string conversion, and test for string properties.

NC...

 

0
NC01
5/23/2006 11:41:23 AM
Reply:

Similar Artilces:

Object of type 'System.DBNull' cannot be converted to type 'System.String' from formview
I have a formview that I am using for input to my datatable.  I am using an objectdatasource that uses a BLL.  This in turn points to my XSD tableadapter. When I test, and only fill in the required fields, I am getting the error Object of type 'System.DBNull' cannot be converted to type 'System.String' I am not sure what field is having the issue.  In my BLL for the Add, I have checked the dates for null and placed the value of DateTime.MinValue.  For the text fields, I have place "" if they are null.  Is this error being create prior to...

Cast from type ''''DBNull'''' to type ''''String'''' is not valid.
How do I avoid getting this error: Cast from type ''''DBNull'''' to type ''''String'''' is not valid. I am trying to get values from the database into a form for updating using a Datareader, SQL is set to allow nulls for certain fields as they are not required but the only way I can get the form to display is by adding a space in SQL. Is there another way around this? Check if it is equal to DBNull.Value first and if it is, don't do the cast.Stanley Tan theSpoke Blog Where in the code does it need to go? I am using the following and it's the profile that isn't always requi...

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

Object of type 'System.DBNull' cannot be converted to type 'System.DateTime'.
Hi, How can I pass null values to a system.datetime? Thanks in advance for the help J   Below is my code:   Public Class Courses     Public Sub Update_Class(ByVal ClassId As Integer, _    ByVal StatusId As Integer, _    ByVal ClassNumber As Integer, _    ByVal TeacherId As Integer, _    ByVal AmountofParticipants As Integer, _    ByVal CourseDate1 As DateTime, _    ByVal CourseDate2 As DateTime, _    ByVal CourseDate3 As DateTime)     Dim myConnection As New SqlConnection(Conn...

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

System.Net.Mail is giving error CS0029: Cannot implicitly convert type 'string' to 'System.Net.Mail.MailAddress'
I'm getting an error while trying to use the wizard to create a form and than pass it the vaibles to Mail. Any help would be much appreciated. SmtpClient smtpClient = new SmtpClient(); MailMessage message = new MailMessage(); try {   message.From = txtEmail.Text; message.To.Add("admin1@yoursite.com"); message.Subject = "Feedback"; message.CC.Add("admin1@yoursite.com"); message.CC.Add("admin2@yoursite.com"); message.IsBodyHtml = false; message.Body = txtMessage.Text; smtpClient.Send(message); lblStatus.Text = "Email successfully sent."; } catch (Exception ex) { lbl...

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"; } } Hey,Doesn't seem to pass the dbnull check.  Try to do:  if ((!DBNull.Valu...

Unable to cast object of type 'System.DBNull' to type 'System.String'.
Hi there, If I add a new event and leave the description field empty the StarterKit seems to throw a big wobbly over the null values in my DB (SQL2000). Have I made a mistake in the installation or something? The problem lies in this line: SharedRoutines.truncate((string)Eval("description")) because description is Null. I want to sort this in this line and I don't want to reply on validators? This is a known issue reported in the Identified Bugs and Fixes for the ClubSite Starter Kit post. I don't think there is one definitive answer. Search on your error message and you'll fin...

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

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'.
Hi All, I am using Sql server 2005 and VS 2005 C#. Can anybody explain howz solve this prob? 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 Error: Line 3496: get { Line 3497: try { Line 3498: ...

Cannot implicitly convert type 'System.DBNull' to 'System.DateTime'
I'm using _StartDate = DBNull.Value;  _StartDate is datetime Somehow its not working when I set to dbnull.value Error 1 Cannot implicitly convert type 'System.DBNull' to 'System.DateTime'   i want to set to null or empty, how do i do that?  thanks.Its all about coding! Dear, the DateTime datatype cannot be null. that is why ur getting this kind of error what u can do is to set the default value for the DateTime variable that u have to the DateTime.MinValue. it will give u a date (1/1/0001) which for sure you can depend on. Happy codingHaissam Abdul MalakMCA...

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

Web resources about - Convert 'System.DBNull' to type 'System.String' ? - asp.net.getting-started

Resources last updated: 12/7/2015 2:52:20 PM