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 valid
I'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"))) %>' />
Line 118:                                <a href='<%# "Events_view.aspx?Eventid=" &Cstr( Eval("ID"))%>'>read more &raquo;</a></p>
Line 119:                            <div class="clearlist">

Source File: C:\Inetpub\Guides\Events_List.aspx    Line: 117

Stack Trace:

[InvalidCastException: Conversion from type 'DBNull' to type 'String' is not valid.]
   Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Object Value) +591
   ASP.events_list_aspx.__DataBinding__control15(Object sender, EventArgs e) in C:\Inetpub\Guides\Events_List.aspx:117
   System.Web.UI.Control.OnDataBinding(EventArgs e) +99
   System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +206
   System.Web.UI.Control.DataBind() +12
   System.Web.UI.Control.DataBindChildren() +216
   System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +216
   System.Web.UI.Control.DataBind() +12
   System.Web.UI.WebControls.Repeater.CreateItem(Int32 itemIndex, ListItemType itemType, Boolean dataBind, Object dataItem) +130
   System.Web.UI.WebControls.Repeater.CreateControlHierarchy(Boolean useDataSource) +454
   System.Web.UI.WebControls.Repeater.OnDataBinding(EventArgs e) +53
   System.Web.UI.WebControls.Repeater.DataBind() +72
   System.Web.UI.WebControls.Repeater.EnsureDataBound() +55
   System.Web.UI.WebControls.Repeater.OnPreRender(EventArgs e) +12
   System.Web.UI.Control.PreRenderRecursiveInternal() +77
   System.Web.UI.Control.PreRenderRecursiveInternal() +161
   System.Web.UI.Control.PreRenderRecursiveInternal() +161
   System.Web.UI.Control.PreRenderRecursiveInternal() +161
   System.Web.UI.Control.PreRenderRecursiveInternal() +161
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1360

Thanks for any help,
Rick
0
RCorgiat
11/29/2005 1:52:41 PM
asp.net.club-site-starter-kit 1219 articles. 0 followers. Follow

9 Replies
4128 Views

Similar Articles

[PageSpeed] 51

Your field is returning null and not '' so you can't convert it to a string.  Just make dop something like:

string sTemp = "";
if (yourField != DBNull.Value)
{
   sTemp = yourField;
}

yourField being the code you use to get your field value.
C# / C++ Developer
0
Kelsey
11/29/2005 4:39:44 PM
Eval takes more than one argument.
Mike Banavige
~~~~~~~~~~~~

Need a site code sample in a different language? Try converting it with: http://converter.telerik.com/
0
mbanavige
11/29/2005 5:24:29 PM
OK, I'm a newbie to ASP and programming in general. I amazed that I even got this far. Should I remove the eval statement?
Thanks,
Rick
0
RCorgiat
11/29/2005 7:20:25 PM

The root problem is that the description of an event was not filled in when it was created and DBNull is being returned from the database as the value for Description, in this case.

The error is occurring in the CStr function rather than the Eval.

I did try to trap entry to truncate, which is a project function, and the code fails before getting there.

The C# version of the project uses Convert.ToString rather than CStr.  I am replacing CStr with Convert.ToString.  It seems to work. 

One of the problems with this type of binding is catching errors and dealing with them.  A nice Try Catch would be nice.  Might also inject a function that checks for DBNull and returns String.Empty. 

I do agree with the post that suggest the author of this Kit get it to work.  How could this error have gotten through any software testing?


Robert Storrs
0
rstorrs
11/29/2005 9:22:49 PM
Thanks Robert! Replacing CStr with Convert.ToString seems to work. I really apreciate the help.

Rick
0
RCorgiat
11/30/2005 5:44:00 AM

Hey maybe you can give me a hand. I get the following error and have no clue on how to fix it. I am just learn .net and would like some help. If you have any suggestions please let me know.

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 145:				Using reader As SqlDataReader = command.ExecuteReader()
Line 146: Do While (reader.Read())
Line 147: settings = New SiteSettings(CInt(reader("SiteID")), CStr(reader("SiteName")), CStr(reader("SiteSlogan")), CStr(reader("SitePageTitle")), CStr(reader("MetaDescription")), CStr(reader("MetaKeywords")), CStr(reader("ThemeName")), CStr(reader("CopyrightCredits")), CInt(reader("EnableRegistration")), CInt(reader("EnableUserThemes")), CStr(reader("SMTP")), CInt(reader("RequiresAuthentication")), CStr(reader("AuthUsername")), CStr(reader("AuthPassword")))
Line 148: Loop
Line 149: End Using

 

0
slipstream77
3/12/2007 3:46:18 PM

I have seen this issue in the past both here and in other areas of the club site as well. I fixed it by removing Cstr then modifying the truncate  function to accept an object as an argument verses a string argument (objects can be set to null, but not strings).

You can then use My_String = My_Object_Name.ToString inside the truncate  function to convert the null or string object back to a string (or empty string).  

The other approach is to simply append an empty string to the db eval as shown below...

 truncate(CStr(Eval("description")&""))

See my club site.... www.jeromessite.com

 


Jerome C. Vernon
0
jeromevernon
3/13/2007 6:05:59 PM

I had this error and read every response I could google.  I later found my problem was easily solved. 

Here is what i was doing wrong was,  I bound the checkbox correctly, then after that,  I selected the property  "checked"  to True.  I wanted the box checked by default. like in html. 

however in vs2005 2.0  this setting will unbind your checkbox.without notifying you of course.   (which would make it not work or bind.)   I did not realize this at first. 

So then when I would create a test record it would save a null value to the database because it was no longer bound. 

Then when I went to update that record it would blow this "Conversion from type 'DBNull' to type 'String' is not valid "   error. 

I would not understand what was happening because it was working prior to this property change. 

Then I toggled off the two-way databinding to see what that would do.  that just made the problem worse, because then when I refreshed schema and rebound the control.

it still was saving nulls.   so.

I also realized i had to make sure in the edit databindings section I had two-way databinding selected. 

 I also realized it did not matter if in the sql table it was set to allow or not to allow nulls.  Although if you set the table to allow nulls you can refresh the table to see precicely when  you are saving nulls or 0 or 1. 

 If you bind a checkbox you cannot also set checked to True.  That is not a default setting.

In the end, I still was not able to set my textbox to true. 

 

 

 


hittem in the head ed.
0
Webmonkeymon
3/16/2007 8:53:49 PM

Aside from unwanted nulls, other issues that come up regarding record creation and updates is the use of reserved characters such as single quotes (‘), required fields and data overflows. In addition there may be some issues with dates and time (default values and valid formats). All this is usually handled with field validation (either using page controls and/or code-behind methods). Keeping in mind that the starter kits are primarily a place to start coding and learning from; there are many ways to do field validation and great validation controls are readily available from the toolbar and the AJAX toolkit.

 

Although some will unquestionably argue the case, sometimes it may be appropriate to handle page update via code-behind in an update button click event. This way field input data can be conditioned and/or alert messages presented to the users prior to updates. It’s really a very simple process and depending on the user alert method desired it supports the utilization of asynchronous post-backs (AJAX update panels) effectively.

 

I hope this doesn’t get everyone more confused (or perhaps even angry) but here is some sample code that illustrates a code-behind (code based) process of data conditioning, operator alert and record creation/update presented in a single concise update method…

 

 

Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate.Click

        'Add or Update record.

        Dim sql As String = ""

        Dim sValue As String = ""

        Dim connection As SqlConnection

        Dim command As SqlCommand

        Dim RecordsAffected As Int32 = 0

        Dim reader As SqlDataReader

        Dim bEdit As Boolean = False

        Dim sTemp As String = ""

        Dim dDate As Date

 

        'Get and condition the vars from the form controls.

        Dim sTitle As String = Mid(txTitle.Text & "", 1, 500)

        sTitle = Replace(sTitle, "'", "''", 1, -1, CompareMethod.Text)

        Dim sURL As String = Mid(txURL.Text & "", 1, 500)

        sURL = Replace(sURL, "'", "''", 1, -1, CompareMethod.Text)

        Dim sDescription As String = Mid(txDescription.Text & "", 1, 5000)

        sDescription = Replace(sDescription, "'", "''", 1, -1, CompareMethod.Text)

 

        'Date... Keep date formatting as system defined.

        sTemp = dtpicker.selectedDateTime & ""

        If Not IsDate(sTemp) Then

            dDate = Now

        Else

            dDate = CDate(sTemp)

        End If

 

        Dim iValue As Integer = CInt(Photopicker1.ImageId.ToString)

        Dim sImage As String = Str(iValue)

        Dim sAlbum As String = albumpick.AlbumID.ToString

        If Trim(sAlbum) = "" Then

            sAlbum = "0"

        End If

 

        'Validate the Location Name and Description.

        If Trim(sTitle) = "" Then

            ServerAlert.OKText = "  OK  "

            ServerAlert.Title = "Error, ""Announcement Title""..."

            AlertText.Text = AlertTextHead

            AlertText.Text += "</br></br>Can not update the Announcement record!"

            AlertText.Text += "</br></br>The ""Announcement Title"" field is empty. Type the ""Announcement Title"" then click the ""Update"" button."

            AlertText.Text += "</br></br></br>" & AlertTextFoot

            ServerAlert.Show()

            Exit Sub

        End If

        If Trim(sDescription) = "" Then

            ServerAlert.OKText = "  OK  "

            ServerAlert.Title = "Error, ""Description Text""..."

            AlertText.Text = AlertTextHead

            AlertText.Text += "</br></br>Can not update the Announcement record!"

            AlertText.Text += "</br></br>The ""Announcement Description"" field is empty. Type the ""Announcement Description"" then click the ""Update"" button."

            AlertText.Text += "</br></br></br>" & AlertTextFoot

            ServerAlert.Show()

            Exit Sub

        End If

 

        If LCase(Trim(hdAction.Value)) = "edit" Then

            sValue = hdId.Value.ToString

            If Not IsNumeric(sValue) Then

                'This should never happen

                Response.Redirect("news_list.aspx")

            End If

            bEdit = True

        End If

 

        connection = New SqlConnection(ConfigurationManager.ConnectionStrings("CurrentSiteDB").ConnectionString)

        connection.Open()

 

        If bEdit = False Then

            'Add the record.

            sql = "INSERT INTO Announcements(title, staticURL, description, itemdate, photo, albumid) "

            sql += "VALUES ('" & sTitle & "', '" & sURL & "', '" & sDescription & "', '" & dDate & "'," & sImage & "," & sAlbum & ") "

            command = New SqlCommand(sql, connection)

            RecordsAffected = command.ExecuteNonQuery()

            command.Dispose()

            command = Nothing

            connection.Close()

        Else

            'Update the record.

            sql = "Select * From Announcements Where Id =" & sValue & " "

            command = New SqlCommand(sql, connection)

            reader = command.ExecuteReader()

            If reader.HasRows Then

                reader.Close()

                command.Dispose()

                'Update the record.

                sql = "UPDATE [Announcements] SET  "

                sql += "[title] = '" & sTitle & "',[staticURL] = '" & sURL & "',"

                sql += "[description] = '" & sDescription & "',[itemdate] = '" & dDate & "',"

                sql += "[photo] = " & sImage & ", [albumid] = " & sAlbum & " "

                sql += "WHERE [Id] = " & sValue

                command = New SqlCommand(sql, connection)

                RecordsAffected = command.ExecuteNonQuery()

                command.Dispose()

            End If

            reader = Nothing

        End If

        command = Nothing

        connection.Close()

        Response.Redirect("news_list.aspx")

 

    End Sub

 

 

 


Jerome C. Vernon
0
jeromevernon
3/19/2007 6:30:25 AM
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.
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...

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 Experts,I am reading data into a datagrid and am checking for nullsHere is the code in the datagrid which checks a function in the code-behind:<ItemTemplate>    <asp:Label id="Label2" runat="server" text='<%# GetPickUpDate(container.dataitem("ActualPickUpDate"))%>'></asp:Label></ItemTemplate> Here is the funtion:Function GetPickUpDate(ByVal DateVal As Date) As String            If Not IsDBNull(DateVal) Then     &nb...

Conversion from type 'DBNull' to type 'String' is not valid.
Hi,it's me again...I'm having error withDim Accesstring As String = ("SELECT     FirstName, LastName, Email, StreetAddress, City, Country, State, Zip, Worknum, googlecheckout, paypal, csftcc, confirmationcode FROM dbo.reservation WHERE (confirmationcode = @concode)")            Dim cmd3 As New SqlCommand(Accesstring, icnnn)            cmd3.Parameters.Add("@concode", SqlDbType.NChar).Value = onlineconfirmationcode.Text   &...

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/14/2016 4:07:51 PM