Cast from type 'DBNull' to type 'String' is not valid. - Help!

I have a problem when I try to read from a table "Ads" in my database and the value of the field is <NULL>.  (I assume that I will come across a field that will be blank.)  I’m not referencing any field in particular.  I am learning .Net through I test project.  When I delete a field in a record, for example "phone" I get following error:

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

I would like to not show the label at all if it's null. For now how do I overcome this Null issue.
I included my code below.
Thank you.
<%@ Import Namespace="System.Data.OleDb" %>

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Web.UI.WebControls.Image" %>
<script runat="server">
Dim ConnectString, SelectStatement As String
Dim Connect As OleDbConnection = New OleDbConnection
Dim Adapter As OleDbDataAdapter = New OleDbDataAdapter
Dim TestCB As OleDbCommandBuilder
Dim TestDS As DataSet = New DataSet
Dim Row As DataRow
Public AdNum As Integer
Public Title As String
Public Description As String
Public Category As String
Public Price As String
Public Phone As String
Public Email As String
Public State As String
Public Posted As Date
Public MyPassword As String
Public Image As String
Public HasErrors As Boolean
Public RowError As String
Sub GetAd(AdNumSent As Integer)
SelectStatement = "Select * From Ads Where AdNum=" & AdNumSent
ConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & server.mappath("Testdb.mdb") & ";"
Connect.ConnectionString = ConnectString
Adapter.SelectCommand = new OleDbCommand(SelectStatement, Connect)
TestCB = New OleDbCommandBuilder(Adapter)
If TestDS.Tables("Ads").Rows.Count > 0 Then
Row = TestDS.Tables("Ads").Rows(0)
AdNum = Row.Item("AdNum")
Title = Row.Item("Title")
Description = Row.Item("Description")
Category = Row.Item("Category")
Price = Row.Item("Price")
Phone = Row.Item("Phone")
Email = Row.Item("Email")
State = Row.Item("State")
Posted = Row.Item("Posted")
MyPassword = Row.Item("MyPassword")
Image = Row.Item("Image")
TitleLabel.Text = Title
DescriptionLabel.Text = Description
PriceLabel.Text = Price
PhoneLabel.Text = Phone
EmailLink.Text = Email
EmailLink.NavigateURL = "mailto:" & Email
StateLabel.Text = State
PostedLabel.Text = Posted
AdImage.ImageUrl = Image
End If
End Sub

Sub PlaceAd
Row = TestDS.Tables("Ads").NewRow
Row.Item("Posted") = CDate(Today)
Adapter.Update(TestDS, "Ads")
End Sub
Sub EditAd
Adapter.Update(TestDS, "Ads")
End Sub
Sub DeleteAd
Adapter.Update(TestDS, "Ads")
End Sub
Private Sub CopyToDS
Row.Item("Title") = Title
Row.Item("Description") = Description
Row.Item("Category") = Category
Row.Item("Price") = CSng(Price)
Row.Item("Phone") = Phone
Row.Item("Email") = Email
Row.Item("State") = State
Row.Item("MyPassword") = MyPassword
Row.Item("Image") = Image
End Sub
Private Sub PostErrors
HasErrors = TestDS.HasErrors
If HasErrors Then
RowError = TestDS.Tables("Ads").Rows(0).RowError
End If
End Sub
<TABLE id="Table1" cellSpacing="0" cellPadding="2" width="100%" bgColor="lime" border="1">
<td bgColor="yellow" colSpan="2"><asp:label id="TitleLabel" runat="server" font-size="12 pt" font-bold="true"></asp:label></td>
<td vAlign="top" width="25%">Description:</td>
<td><asp:label id="DescriptionLabel" runat="server" font-size="12 pt" font-bold="true"></asp:label></td>
<td width="25%">Price:</td>
<td>$<asp:label id="PriceLabel" runat="server" font-size="12 pt" font-bold="true"></asp:label>
<td width="25%">Phone:</td>
<td><asp:label id="PhoneLabel" runat="server" font-size="12 pt" font-bold="true"></asp:label></td>
<td width="25%">Email:</td>
<td><asp:hyperlink id="EmailLink" runat="server" font-size="12 pt" font-bold="true"></asp:hyperlink></td>
<tr> <td width="25%">Location:</td>
<td><asp:label id="StateLabel" runat="server" font-size="12 pt" font-bold="true"></asp:label></td>
<td width="25%">Posted:</td>
<td><asp:label id="PostedLabel" runat="server" font-size="12 pt" font-bold="true"></asp:label></td>
<td width="25%">Image:</td>
<td><asp:Image id="AdImage" runat="server" /></td>

6/17/2004 3:37:44 AM 91979 articles. 4 followers. Follow

4 Replies

Similar Articles

[PageSpeed] 4

Right. So, for each column which can be null, you need to check this in the assignment:

If Not myRow.IsNull("SomeColumn") Then
someVariable = Ctype(myRow("SomeColumn"),String)
End If
--Brian Desmond
Windows Server MVP - Directory Services
6/17/2004 3:39:16 AM
I understand about testing each column that can be NULL, but where do i place the statement.  Could you get me an example or some more instruction.

Thank You.
6/17/2004 3:51:13 AM
Ah. Sorry:

AdNum = Row.Item("AdNum")
If Not myRow.IsNull("AdNum") Then
someVariable = Ctype(myRow("AdNum"),String)
End If
--Brian Desmond
Windows Server MVP - Directory Services
6/18/2004 2:23:22 AM

A slightly more elegant way would be to call the .ToString method on any values that could possibly be null, e.g.
AdNum = Row.Item("AdNum").ToString


Peter Brunone
Do the impossible, and go home early.
6/18/2004 6:37:56 AM

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

Cast from type 'DBNull' to type 'String' is not valid
I REALLY need some help, so here goes. The following function does work as long as the "mail" field in the database isn't NULL. As you can see I have tried a couple of ways to check for a NULL value but none of them seem to work. What's supposed to happen is the function checks to see whether or not a user has an email address in the database. If so, then the email address gets returned, if no email address then I need something back from the function so I can go about another way to get the info to the user. Public Function GetReqByEmail(ByVal reqby As String) As String...

Cast from type 'DBNull' to type 'String' is not valid.
Ok, that is the error... "Cast from type 'DBNull' to type 'String' is not valid. " I am filling a DataSet from the db and some fields are empty. Reading from it and placing the info into a label. Code below.... Sub getProductInfo() Dim DSprod2 As New DataSet() Dim MyCommand As OleDbDataAdapter sql = "Select * from tblProducts Where fldNum = " & intfldNum MyCommand = New OleDbDataAdapter(sql, conn) MyCommand.Fill(DSprod2, "tblProducts") lblProd.Text = DSprod2.Tables("...

Cast from type 'DBNull' to type 'String' is not valid.
Hi, I have a page with several's a "change your account" page. One of the parameters is presented as a label instead since it is not changed ON THIS PAGE. It needs to be NULL when the account is created and entered later. But when the page loads, I get the above error. The account row is loaded from a business object LoadFromId(). How can I load the page even though this label data is NULL to start with? relevent code below. <asp:Label ID="lblDDAccount" Runat="server"></asp:Label>------If currentUser.DDAccount = "" Then       &...

Cast from type 'DBNull' to type 'String' is not valid
Hi,  I have an old website and old database (SQL 2000).  I add new column "ImageURL' to database, so all data (several thousand items) are "NULL" (actually is dbNull) under this column.  In searchResult.aspx page, inside the datagrid, I add a colummn call "Image" <code> <asp:datagrid id="dgSearchResult" runat="server"><Columns><asp:TemplateColumn HeaderText="Image" ItemStyle-Width="55px" ItemStyle-HorizontalAlign=Center> <ItemTemplate> <asp:Image ID=ThumbImage Wi...

Cast from type 'DBNull' to type 'String' is not valid.
On the viewproduct page if any of the db fields referenced in the SP are empty you get the above error, the error originates in the productsDB.vb file as follows myProductDetails.ModelNumber = CStr(parameterModelNumber.Value) myProductDetails.ModelName = CStr(parameterModelName.Value) myProductDetails.ProductImage = CStr(parameterProductImage.Value).Trim() myProductDetails.UnitCost = CType(parameterUnitCost.Value, Decimal) myProductDetails.Description = CStr(parameterDescription.Value).Trim() OK I can make ...

Cast from type 'DBNull' to type 'String' is not valid.
How would I check to make sure my SQL db is not pulling a null value? I'm using the following code and I get the 'Cast from type 'DBNull' to type 'String' is not valid.' error. If (dtrUserDetails("D_Address2") Is System.DBNull.Value) Then _Address2 = "" Else _Address2 = dtrUserDetails("D_Address2") End If Any help would be much appreciated. Change your line to _Address2=dtrUserDetails("D_Address2") & "" The empty string in the end will convert the filed to a string ...

Cast from type 'DBNull' to type 'String' is not valid
 Hi all,Sorry to be posting here on what is probably a common enough error but I am at my wits end with this one. Quite simply I call an Update stored procedure in my code, passing in a number of paramaters. However, when I try to run the code, the following exception is thrown:Cast from type 'DBNull' to type 'String' is not validI'm really not sure what the problem is here. I have tried hardcoding values for the string values with no success also, as well as using the IsNothing function, but no joy there eitherI would really appreciate someones help as I spent 2 hou...

Cast from type 'DBNull' to type 'String' is not valid #2
G'day, Puzzled by this. The error occurs on the field "Mobile" yet its format is exactly the same as the other fields. In otherwords I can remove the line of code dealing with "Mobile" and it will function. Can anyone explain? The error is : Cast from type 'DBNull' to type 'String' is not valid. <%#ifPresent("Phone:",Container.DataItem("Phone"))%> <%#ifPresent("Fax:",Container.DataItem("Fax"))%> <%#ifPresent("Mobile:",Container.DataItem("Mobile"))%> <%#ifPre...

Cast from type 'DBNull' to type 'String' is not valid. #2
I think this is a bug, the database of Products are allowed to have "Null" Value, but when you do have one, the store is crashed with subjected message, I have found a solution to use View to change the Null value into something when run the SQL store procedure, but I don't know if is there anyway from "Class" side to solve it. Always check for Null before trying to convert the value to a string or assign to a text or label. Try this: If Not(IsDbNull(drProducts("foo"))) Then ...insert your code to display here... End If mix it up! www.devalch...

Cast from type 'DBNull' to type 'String' is not valid. #3
help anybody.. it has been 2 weeks since i got out of this error.. please anybody share their insights on this here is my code. Populate Struct using Output Params from SPROC Line 86: myCustomerDetails.FullName = CStr(parameterFullName.Value) ---ERROR!! Line 87: myCustomerDetails.Password = CStr(parameterPassword.Value) Line 88: myCustomerDetails.Email = CStr(parameterEmail.Value) Of course. They are not the same thing. casting requires the objects to implement either a common ancestor or interface to cast to. Use ToStrin...

Cast from type 'DBNull' to type 'String' is not valid. #3
Hi Everyone, I am trying this very simple select statement and storing my information into arrays but i am receiving the above error whenever the field has a NULL as value.I have looked at other similar post in this forum and know that i need to check if the string is empty but somehow i do not know the exact syntax to do this check.  Please help. Dim conAct As SqlConnectionDim cmdSelectAct As SqlCommandDim dtrAct As SqlDataReaderconAct = New SqlConnection("etc etc")conAct.Open()cmdSelectAct = New SqlCommand("Select EMPLID,USERID etc etc  from TABLE where STATUS='I'", conAct)...

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

Cast from type 'DBNull' to type 'String' is not valid. #2
i have an login page which use e-mail address and password to login , once the system comfirm this is valid login it get customer details and in my login page i have the following code Dim loginsystem As onlineshop.Customers = New onlineshop.Customers() Dim customerId As String = loginsystem.customer_login(login.email_address, login.password) If customerId <> "" Then Dim customerDetails As onlineshop.customer_Detail = loginsystem.Get_Customer_Details(customerid) and at the onlineshop.customer_detail function i have the following ...

Cast from type 'DBNull' to type 'String' is not valid. Error
Hi, Can anyone help me with an error I am receiving "Cast from type 'DBNull' to type 'String' is not valid."  I am creating an aspx page in VB.NET, please find attached code causing error.objCmd = New SqlCommand("USP_DisplayEmbarkDetails", objConn)  objCmd.CommandType = CommandType.StoredProcedure  objCmd.Parameters.Add("@BranchID", lblGetBranchID.Text)  objConn.Open()  objRdr = objCmd.ExecuteReader()    While objRdr.Read     lblBranchName.Text=objRdr("BranchName")    lblBranchID.Text=objRd...

Web resources about - Cast from type 'DBNull' to type 'String' is not valid. - Help! -

Resources last updated: 12/12/2015 8:55:02 AM