'DBNull' to type 'String' is not valid

 I am using asp.net 3.5 with ajax. Here is my code behind the webpage:

     Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        'Connection string
        Dim connStr As String = ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("_database/AttorneyApp.mdb"))

        'Establish connection
        Dim conn As OleDbConnection = New OleDbConnection(connStr)

        'Create commands
        Dim command As New OleDbCommand("SELECT * FROM Clients", conn)

        'Create dataAdapters
        Dim clientAdapter As New OleDbDataAdapter(command)

        'Create DataSets
        Dim ds As New DataSet

        'Create Clients Tables
        Dim clients As DataTable = ds.Tables.Add("Clients")

        'Fill Tables

        'Display Data
        clientIdTxt.Text = clients.Rows(0).Item("ClientId")
        firstNameTxt.Text = clients.Rows(0).Item("FirstName")
        lastNameTxt.Text = clients.Rows(0).Item("LastName")
        addressTxt.Text = clients.Rows(0).Item("Address1")
        address2Txt.Text = clients.Rows(0).Item("Address2").ToString()

    End Sub


sometimes address2Txt.Text can obviously be left blank. However, when it is I get the following error message:


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

how do I correct this problem? I have looked at the following thread and the solutions did not work for me: http://forums.asp.net/p/961846/1194730.aspx#1194730


Any suggestions?


1/15/2008 9:16:28 PM
asp.net.object-datasource 16182 articles. 0 followers. Follow

3 Replies

Similar Articles

[PageSpeed] 49

Use Convert.ToString(object) instead of the object.ToString method. You can't call ToString on null/Nothing.



Please Mark As Answer posts that helped you.

"If we learn from our mistakes, I should be brilliant by now."

MCTS - .NET Framework 2.0: Web Applications
1/15/2008 9:30:32 PM

You can't convert DBNull to a string, so you need to check if that value is there before you try to grab it.

address2Txt.Text = IIf(clients.Rows(0).IsNull("Address2"),  "", clients.Rows(0).Item("Address2"))
Mark Doyle
Doyle ITS
1/16/2008 12:04:18 AM

 Thanks! It worked perfect when I used Convert.ToString()

1/16/2008 2:10:33 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...

Name: haznen Email: haznenatyahoodotcom Product: Gran Paradiso Alpha 8 Summary: '''''''''''''''''''' Comments: '''''''''''''''''''''''''''''''''''' Browser Details: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9a1) Gecko/20061204 UGES/ GranParadiso/3.0a1 From URL: http://www.mozilla.org/projects/granparadiso/ Note to readers: Hendrix gives...

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

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

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

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

Cast from type 'DBNull' to type 'String' is not valid.
Hi, I have a page with several textboxes...it'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 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.
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 ...

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

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

Web resources about - 'DBNull' to type 'String' is not valid - asp.net.object-datasource

Resources last updated: 12/31/2015 9:10:11 PM