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

On line 65 of Events_Calendar.aspx-

<div style="padding: 3px;">

<asp:HyperLink ID="HyperLink1" runat="server" Text='<%#Eval("title") %>' NavigateUrl='<%# "Events_view.aspx?Eventid=" &CStr( Eval("ID"))%>'

ToolTip='<%# truncate(CStr(Eval("description"))) %>' /></div>

The debugger tells me "InvalidCastException unhandled by user code"

I found out that the data entry form for events allows the user to leave the description field empty.  So this translates to NULL in the SQL Server 2005 database.  the NULL value in the description field causes the exception, I can make it go away by replacing the NULL value with a blank value, directly editing the table using SQL Server Management Studio Express.

I am new to this. Any number of solutions would work, but the complexity of these data entry forms has me beating my head on the desk. I am familiar with building forms for desktop apps in VB and VFP)

Any real simple answer to one of these questions would be helpful.

Can I force a default value to be an empty string (or anything) instead of NULL on the data entry form when a user does not enter anything in a field?  I could use either a field or record validation rule, or simply a default value property - how is this done?

Or, how would one force a user to fill out a field on the Events_Edit.aspx form?

Thanks

 

 

0
lutz2
2/10/2006 7:35:59 PM
asp.net.club-site-starter-kit 1219 articles. 0 followers. Follow

20 Replies
1084 Views

Similar Articles

[PageSpeed] 50

Check out this tip from ASPNet101.com:
http://aspnet101.com/aspnet101/tips.aspx?id=27
David Wier
MCP/ASPInsider
ASPNet101.com - where to look first!
Please Vote for ASPNet101 - 'Best Community Resource'!
Control Grouper - easily control properties for multiple controls with one control!
Calendar Express - The Best HTML Calendar Generator on the web!
(Please 'Mark as Answer' when it applies)
0
augustwind
2/10/2006 7:43:07 PM

Lacking the patience to change more stuff, my solution is to avoid trying to perform the operation that may fail. So I just changed the failing CStr() function with myCStr() in the pages where it is failing.

<script runat="server">
function myCStr(Byval test as object) as String
   if isdbnull(test) then 
      return("")
   else
      return CStr(test) 
   end if
end function

</script>

0
lutz2
2/10/2006 8:25:54 PM

To force a description use Required Field validation


You can add requiredfieldvalidator using design view.  or use this code.

In Events_Edit.aspx

Replace in InsertItemTemplate

<td class="formlabel">

<asp:Label ID="Label1" runat="server" Text="Description:" />

</td>

<td align="left">


With


 

<td class="formlabel">

<asp:Label ID="Label1" runat="server" Text="Description: Required" />

<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="descriptionTextBox"

ErrorMessage="Description Required!">Description Required!</asp:RequiredFieldValidator></td>

<td align="left">


and Replace in EditItemTemplte


 

<td class="formlabel">

<asp:Label ID="Label1" runat="server" Text="Description:" />

</td>

<td align="left">


With


 

<td class="formlabel" style="height: 180px">

<asp:Label ID="Label1" runat="server" Text="Description: Required" />

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="descriptionTextBox"

ErrorMessage="Description Required!">Description Required!</asp:RequiredFieldValidator></td>

<td align="left">

 

 


Support@aspsksolutions.com

0
MaineOne
2/10/2006 9:26:12 PM
Great fix, just what I was after
Regards

<<<Bryan Avery>>>


Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue.
0
Coppermill
2/17/2006 11:02:38 AM

The fix I decided to go with:

Update the insert and update SQL statements to use isnull(@description,'') instead of just @description.

A blank string will always be stored in the database instead of a null then.

0
GavinPollock
3/28/2006 11:59:15 AM
GavinPollock:

The fix I decided to go with:

Update the insert and update SQL statements to use isnull(@description,'') instead of just @description.

A blank string will always be stored in the database instead of a null then.



There is really no reason to store a 'blank' (empty string) to get around this issue.  After working with Microsoft Access for 14 years, Nulls are a fact of life ... and really not a problem.  You just have to deal with them appropriately.  If you store an empty string, you may have other issues down the road ... if for example ... for whatever reason ... you need to test for Null in the Description field - the default value for a new record - but - forget that you have put an empty string in that field. 
The best approach here so far is the Function given by lutz2:

<script runat="server">
function myCStr(Byval test as object) as String
   if isdbnull(test) then 
      return("")
   else
      return CStr(test) 
   end if
end function
</script>

Better yet would be to use an IIF in the line of code ToolTip='<%# truncate(CStr(Eval("description"))) %>'  .... replacing a Null with "" (empty string) on the fly.  Unfortunately, I can't quite get the syntax right for this.  Lutz2's function essentially does this.

And really ... why ... is it necessary to take the CStr of the Eval of the Description field??  The Description field is already a String (text) data type!  This error would not even occur if you didn't use CStr and Eval!  And actually, not sure Truncate is necessary either!

And FOR SURE ... there is no reason to 'require' the Description field and do a validation !!

BTW ... this same issue/error occurs in the News section ... where I also used lutz2's fix

EOP.

0
DatabaseMX
3/29/2006 7:24:26 AM

Can anyone give me an example of this fix? I am getting the same error using the events page and don't know exactly how to change this code:

 

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

0
andyzamm
4/12/2006 4:14:46 AM

1) in the Events_List.aspx, add the myCStr function to the code at the top of the page, inside the script tags

<script  runat="server">

(other code)

...

function myCStr(...

...

</script>

 

In any of the lines that cause errors use the myCStr function. I dont recall what was there previously,

probably the regular CSstr(...), but this example is shortly after the first <!-- begin news item -->

<asp:Label ID="descriptionLabel" runat="server" Text='<%# truncate(myCStr(Eval("description"))) %>' />

 

0
lutz2
4/12/2006 1:09:10 PM

I feel like such a dummy... It worked with no problems. Thanks.

 

AZ

0
andyzamm
4/12/2006 6:22:51 PM

Don't feel that way, I'm glad to help.  I'm new to this.  I've spent hours or even days of fighting with difficult issues, to find that the needed changes are "simple".   Luckily I know pre-.NET VB, C and databases.

Until just now, I did not know how to make the function global for the whole website, so that the function would not need to be declared in the script portion of every page where it is needed.  

The answer appears to be in ~/App_Code/Shared_routines.vb 

Place the function in Shared_ routines.vb, and declare it public like this:

Public function ....

   ....

   Return ...

End Function

I have not tried this yet, but it should work

 

0
lutz2
4/12/2006 10:54:14 PM

Thanks each of the contributors to this! Took me 12 tries not really knowing what I'm doing but it's working...for now(lol)

Dravend

0
Dravend
4/18/2006 7:59:09 PM

Hi,

       Can you offer me any help in fixing this issue in c# ?


J. Jones
0
hazardjonesjj
7/26/2006 6:45:23 PM
<rant>

Hate to bump this old message, but I really disagree with the notion that "nulls are a fact of life". They are if you let them, and there really is a world of difference between Access databases and enterprise scale relational models.

In a pure relational model (Boyce Codd form, 3rd +, etc), a traditional null value means that an attribute of an entity is not defined. Because you (should) have built your model correctly, an attribute that may or may not exist for a given entity simply means that there is no relationship.

If you have employees, some of which are sales people, you don't place a "salesGroup" column in the employee table, and then just have nulls for the employees that aren't in that group. Well I suppose you can, but it's pretty Mickey Mouse to be honest.

Where you will run into nulls, even with a relational model, is generally when you get into left outer joins (or any outer join for that matter), because you're intentionally saying "get me everything from the employee table, and match the sales table. If there's no match, I still want the employees, and just give me nulls for the difference". But now you are controlling the nulls, and they exist at query time, and aren't stored anywhere.

Sorry to get on a relational-holier-than-thou trip, but generally the only reason I have ever seen (in the 10 years I've been doing data modeling and development) for nulls in a relational database is laziness, a poorly defined schema, and more often than not, developers who simply don't understand what they're doing.

</rant>
0
eraza
8/11/2006 6:27:15 PM

I wouldn't say that the folks who created this don't know what they are doing, but why not just update the stored procedure, PagedUpcommingEventList, to not return nulls for the description field?

For example:

SELECT Events.id, Events.starttime, Events.title, ISNULL(Events.description, '') AS description, Events.photo,
      Locations.title AS locationname
   FROM Events LEFT OUTER JOIN Locations ON Events.location = Locations.id
   WHERE (Events.starttime > @keydate OR
         (Events.starttime = @keydate) AND (events.id > @keyid))
   ORDER BY Events.starttime asc, Events.id asc

0
SwissPinoy
10/28/2006 5:16:50 PM

I converted the above function to c# and when I place it in Event_list.aspx I get complie error for isDBnull not defined correctly. Error:The name 'IsDBNull' does not exist in the current context    C:\club_rtm_v1_cs\Events_List.aspx . How can I fix it. any suggestion will be appricated.

 public string myCStr(object test)
    {
        if ( isdbnull(test))
        {
            return ("");
        }
        else
        {
            return System.Convert.ToString(test);
        }
    }
 

 

thanks 

0
skapoor
11/12/2006 6:35:59 PM
Change isdbnull(test) to 

if (test 

is DBNull)
0
allankn
11/13/2006 6:48:34 PM

thanks allankn it worked .

if(test is DBNull)

 

 sk

0
skapoor
11/14/2006 3:08:42 PM

when i attempt to add event #4 i get this message:

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

Source Error:

Line 64:                     <div>
Line 65:                         <p>
Line 66:                             <asp:Label ID="descriptionLabel" runat="server" Text='<%# truncate(CStr(Eval("description"))) %>' />
Line 67:                             <a href='<%# "Locations_view.aspx?Locationid=" &Cstr( Eval("ID"))%>'>more details &raquo;</a></p>
Line 68:                         </p>

Source File: F:\hshome\mtvjc\mtvernonjaycees.org\Locations_Picker.ascx    Line: 66
I have tried all of the solutions, I keep an extra copy of all of the buggy related files for practice. I am so new at this my umbilical is yet to dry. I can do a poke and hope, try to follow the error messages and fly from there. the site is up and running, http://mtvernonjaycees.org/ but i cannot get past this barrier. I need help badly, but not bad helply.

Obi Wan, my force is weak and yoda is drunk, can you help

0
NJCorrea
1/24/2007 3:45:45 AM
Before you create a method against this item, you must first check to make sure it is NOT Null - - you're expecting a string here - instead the results are Null - If you make sure to ONLY do this method against a string (if it's not null), it should work
David Wier
MCP/ASPInsider
ASPNet101.com - where to look first!
Please Vote for ASPNet101 - 'Best Community Resource'!
Control Grouper - easily control properties for multiple controls with one control!
Calendar Express - The Best HTML Calendar Generator on the web!
(Please 'Mark as Answer' when it applies)
0
augustwind
1/24/2007 3:12:04 PM

Same problem with "Conversion from type 'DBNull' to type 'String' is not valid. " Please help!

 

Line 346:                                                             ByRef oList As List(Of IPClass))
Line 347:            Do While returnData.Read()
Line 348:                Dim oItem As IPClass = New IPClass( _
Line 349:                                               CInt(returnData("IPStatusID")), _
Line 350:                                               CStr(returnData("LogonID")), _

0
sabena248
12/26/2007 4:46:23 PM
Reply:

Similar Artilces:

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

Conversion from type 'DBNull' to type 'String' is not valid
I get an error (Conversion from type 'DBNull' to type 'String' is not valid.) when I try to assign a field value to a text box using the datareader. Is there code that will fix this error?  wrap an IF check around the retrieval and check for DBNull you'll need to check for null first, before you assign it - - Something like: if Not dr("Yourfield") is System.DbNull.Value then...........David WierMCP/ASPInsiderASPNet101.com - where to look first!Please Vote for ASPNet101 - 'Best Community Resource'!Control Grouper - easily control pr...

Conversion from type 'DBNull' to type 'String' is not valid
I get this error when I try to add an event:Conversion from type 'DBNull' to type 'String' is not validI've been able to add events before, but all of the sudden I'm getting the error...Here is the output of the error:Exception Details: System.InvalidCastException: Conversion from type 'DBNull' to type 'String' is not valid.Source Error: Line 115: </h3> Line 116: <p> Line 117: <asp:Label ID="descriptionLabel" runat="server" Text='<%# truncate(CStr(Eval("description"))) %>' />...

Conversion from type 'DBNull' to type 'String' is not valid...
Thanks for your time.  Getting following error when grid source populates a rows Date field with Null:     - Exception Details: System.InvalidCastException: Conversion from type 'DBNull' to type 'String' is not valid.It works works when I filter the nulls out, but I need to show all rows in the grid. Boils down to:  a) How could I maintain a blank value in the grid and cast this properly to include all rows?    < or >  b) Is there a way to default a value that isnt a date (to avoid the null & keep the IsDate logic as is)  c) ...

Conversion from type 'DBNull' to type 'String' is not valid
Hello Friends            How are you?? Friends i am getting problem in SQL Server 2005. I am deployng web application on production server as well as Databse also. In production server i inserted new field in all tables which is rowguid and its type is uniqueidentifier. The default binding for this field is newsequentialid(). In some pages it works ok but in some places it generates error like 'Conversion from type 'DBNull' to type 'String' is not valid'. Can anybody help me to solve this problem. Its urgent so plz re...

Conversion from type 'DBNull' to type 'String' is not valid
Hello! All,I try to use ObjectDataSource with business layers and used the code given by SDK 2.0. But I got the following message: Conversion from type 'DBNull' to type 'String' is not valid.  I couldn't figure out what 's the problem and felt sorry about this.I attached my code below.  Can anyone help me out of it. Thanks a lot! Vivia  Error Massage: 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 ...

Conversion from type 'DBNull' to type 'String' is not valid
I am using Jeremy's Personal Web Site, which I must say is great.  I have uploaded the site to my GoDaddy web hosting account and created the database tables.  I created an entry for a user and for the site_settings.  I am getting the following error: Conversion 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: C...

I get Conversion from type 'DBNull' to type 'String' is not valid.
I get the following errors when I try and access certain pages.  It is caused by not populating all the text boxes with data and subsequent viewing causes these conversion errors.  Does any one else experience this?  How have you guys worked around this problem? Conversion 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: Conversion f...

Conversion from type 'DBNull' to type 'String' is not valid #2
I'm getting a error message saying: Server Error in '/' Application. Conversion 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: Conversion from type 'DBNull' to type 'String' is not valid.Source Error: Line 113: </h3> Line 114: ...

Conversion from type 'DBNull' to type 'String' is not valid #2
i have with my DB fetch content is Ogject class so i am not use any dataset or datatable but i have problem when field in DB is empty i can insert DBNull in string like this curr.visible = r("visible") curr.title = r("title")curr.description = r("description") curr.price = r("price")   how can i  solve this problem without put if with every insert code fedailr:curr.visible = r("visible") curr.title = r("title")curr.description = r("description") curr.price = r("price") So I assume r ...

Bound TextBox error: Conversion from type 'DBNull' to type 'String' is not valid
 Hi,I use DataSet designer to generate my strongly typed datasets and to bind my FormView to a Business Layer (BLL). The BLL uses the generated Dataset classes. I have a column  in the DB of type string. The column is bound to a textbox like this:Text='<%# Bind("Local") %>'  If the column has a value, thingts work well, but  When the column has a null value, I get the error: Conversion from type 'DBNull' to type 'String' is not validWhat can I do Please? Thanks a lot, I appreciate your taking the time to help me. ...

Conversion from type 'DBNull' to type 'Date' is not valid
I'm using VWD 2005 and have a grid on the page. In that grid, there'sa column that is of date/time type. Nulls are allowed in this column.I'm having problems when trying to edit this date column.I've converted the column to a template and changed theEditItemTemplate from a textbox to a calendar. If a date previouslyexisted for the record being edited, the update action works. If thedate was previously NULL and then a date is chosen via the calendar I get the error. How do I work around this? Charlie Here's my code line:<EditItemTemplate> <asp:Calendar ID="Calendar1" run...

Web resources about - Conversion from type 'DBNull' to type 'String' is not valid. - asp.net.club-site-starter-kit

Resources last updated: 1/16/2016 9:27:51 AM