vb.netms-access-2010oledbconnectionoledbcommanddbnull

How to ignore eror message "dbnull to string is not valid" and dont load empty cells to my vb form


When I click search button error occurs conversion dbnull to type string is not valid.

I think there's no data in some cells in my database.

its not a problem to have empty cells and if there are empty cells I don't want to load them to my form.

Here's what I tried ButtonClickEvent :

     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        
        con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Dimuth De Zoysa\Documents\divimaga_DB.accdb")
        cmd = New OleDbCommand("SELECT * FROM MainE WHERE Job ='" + ComboBox1.Text + "'  ", con)

        con.Open()
        dr = cmd.ExecuteReader()

        While dr.Read
            jobid = dr("JobID")
            TextBox1.Text = dr("PROCEDURE")
            TextBox2.Text = dr("ReleventDocuments")
            TextBox3.Text = dr("ImportantPoints")
            TextBox4.Text = dr("officer")
        End While

        con.Close()
    End Sub

Solution

  • The code you have wouldn't compile with Option Strict On even if there were no nulls in the data. That means it's bad code because Option Strict should pretty much always be On. The Text property of a TextBox is type String, while you're assigning Object references to those properties. You should be casting or converting to type String already. If you call ToString on each field value then you kill two birds with one stone because null fields will contain DBNull.Value and calling ToString on that returns an empty String.

    TextBox1.Text = dr("PROCEDURE").ToString()
    TextBox2.Text = dr("ReleventDocuments").ToString()
    TextBox3.Text = dr("ImportantPoints").ToString()
    TextBox4.Text = dr("officer").ToString()