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 »</a></p>
Line 119: <div class="clearlist">
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?
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
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...
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.
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…
ProtectedSub btnUpdate_Click(ByVal sender
AsObject,
ByVal e As System.EventArgs)
Handles btnUpdate.Click
'Add or Update record.
Dim sql AsString = ""
Dim sValue AsString = ""
Dim connection As SqlConnection
Dim command As SqlCommand
Dim RecordsAffected
As Int32 = 0
Dim reader As SqlDataReader
Dim bEdit AsBoolean = False
Dim sTemp AsString = ""
Dim dDate AsDate
'Get and condition the vars from the form controls.
Dim sTitle AsString = Mid(txTitle.Text &
"", 1, 500)
RCorgiat
Member
35 Points
7 Posts
Conversion from type 'DBNull' to type 'String' is not valid
Nov 29, 2005 12:52 PM|LINK
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:
Source File: C:\Inetpub\Guides\Events_List.aspx Line: 117
Stack Trace:
Thanks for any help,
Rick
Kelsey
Contributor
4222 Points
797 Posts
Re: Conversion from type 'DBNull' to type 'String' is not valid
Nov 29, 2005 03:39 PM|LINK
string sTemp = "";
if (yourField != DBNull.Value)
{
sTemp = yourField;
}
yourField being the code you use to get your field value.
mbanavige
All-Star
134980 Points
15429 Posts
ASPInsiders
Moderator
MVP
Re: Conversion from type 'DBNull' to type 'String' is not valid
Nov 29, 2005 04:24 PM|LINK
RCorgiat
Member
35 Points
7 Posts
Re: Conversion from type 'DBNull' to type 'String' is not valid
Nov 29, 2005 06:20 PM|LINK
Thanks,
Rick
rstorrs
Member
65 Points
14 Posts
Re: Conversion from type 'DBNull' to type 'String' is not valid
Nov 29, 2005 08:22 PM|LINK
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?
RCorgiat
Member
35 Points
7 Posts
Re: Conversion from type 'DBNull' to type 'String' is not valid
Nov 30, 2005 04:44 AM|LINK
Rick
slipstream77
Member
2 Points
1 Post
Re: Conversion from type 'DBNull' to type 'String' is not valid
Mar 12, 2007 03:46 PM|LINK
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:
jeromevernon...
Member
171 Points
69 Posts
Re: Conversion from type 'DBNull' to type 'String' is not valid
Mar 13, 2007 06:05 PM|LINK
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
Webmonkeymon
Member
109 Points
97 Posts
Re: Conversion from type 'DBNull' to Here is simple solution type 'String' is not valid -- not ...
Mar 16, 2007 08:53 PM|LINK
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.
jeromevernon...
Member
171 Points
69 Posts
Re: Conversion from type 'DBNull' to type 'String' is not valid
Mar 19, 2007 06:30 AM|LINK
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