Click here to Skip to main content
15,888,984 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi there I'm a newbie at vb.net, I just want to ask how to fix this error.
Here's my code:
Thank you very much :)
VB
Private Sub btnview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnview.Click
    cn()
    str = InputBox("Enter Student Number", "Search by student number")
    sql = "select count (*) from table1 where stnum = '" & str & "'"
    com = New OleDbCommand(sql, con)
    If com.ExecuteScalar <> 0 Then
        sql = "select * from table1 where stnum='" & str & "'"
        com = New OleDbCommand(sql, con)
        dr = com.ExecuteReader
        dr.Read()
        txtstnum.Text = dr(0)
        txtstname.Text = dr(1)
        txtgender.Text = dr(2) 'my error is here
        txtage.Text = dr(3)
        txtcourse.Text = dr(4)
        txtyear.Text = dr(5)
        txtbdate.Text = dr(6)
        txtadd.Text = dr(7)
        txtcontact.Text = dr(8)
        PictureBox1.ImageLocation = "C:\Users\FRK\Documents\Visual Studio 2010\Projects\T_SIS\T_SIS\bin\Debug\studpics"
        dr.Close()
        con.Close()
    Else
        MessageBox.Show("Record not found", "Message")
        con.Close()
    End If
End Sub
Posted
Updated 11-Oct-14 23:13pm
v2

1 solution

Quote:
Conversion from type 'DBNull' to type 'String' is not valid.
That means the value coming from database is null. So you have to check if that is null or not before reading that.
VB
txtgender.Text = If(IsDBNull(dr(2)), "", CStr(dr(2)))

I would also suggest two things here.

1. You should mention column names instead of * in the query.
2. Instead of index, read the column. Instead of dr(2), you should read like dr("Gender").
 
Share this answer
 
Comments
DVorahck 12-Oct-14 4:55am    
Thank you! ^_^
Please accept the answer and up vote. :)
Maciej Los 12-Oct-14 16:01pm    
+5!
Thanks a lot Maciej. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900