Search code examples
visual-studio-2010richtextboxdatareaderexecutereader

How to use DataReader from Oledb and get results in Richtextbox


Dim srch As String
        srch = ccode.Text
        conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + IO.Directory.GetCurrentDirectory + "\ptdr.accdb"
        cmd.Connection = conn
        conn.Open()

        Dim dsrch As New OleDbCommand("SELECT pname, page, vdate, psex, summer, bldp, blds, photh, diag, rl, trtmnt, nvdate FROM ptnt_data WHERE pcode = " & srch & "", conn)
        Dim rdr As OleDbDataReader = dsrch.ExecuteReader()
        Dim dg As String = ""

            'diagnosis'
            dg = rdr.GetString(8).ToString()
            If String.IsNullOrEmpty(dg) Then
                diag1.Text = ""
            ElseIf String.IsNullOrWhiteSpace(dg) Then
                diag1.Text = ""
            Else
                diag1.Text = dg

            End If

It works fine but when I search for a null it gives an error. It says that I've an error at the line of

dg = rdr.GetString(8).Tostring()

any suggests?


Solution

  • rdr.GetString(8).ToString()
    

    if rdr.GetString(8) is null this is a classic null reference exception

    rdr.GetString(8) IS a string so just remove the .ToString()

    As per my comment below you can only run GetString if the DB has an underlying type of string for this data, what is the datatype of column diag?

    (ie run rdr.GetFieldType(8) in the debugger and provide the type name)

    As you have confirmed this is a string type and the issue is just with null handling (sorry i didn;t spot that from your question) you need:

    If rdr.IsDBNull(8) Then diag1.Text = "" Else diag1.Text = rdr.GetString(8) EndIf
    

    Which should replace everything from Dim dg... down