Question Displaying data in text boxes from Access Database

clcservices

New member
Joined
Oct 6, 2010
Messages
2
Programming Experience
Beginner
Hi,

I'm trying to link my VB.Net project to an Access Database and get information from the database to appear in textboxes. I have succeeded in doing this except for one problem. If the data type in the database is set to "Text" the VB application crashes with a 'System.NullReferenceException' but if the data type is set to "Number" it works perfectly. My code I have to do the search is as follows;

Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Try
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=E:\EquiScore 2011\EquiScore Dressage Scoring\EquiScore_Database.mdb;")
'provider to be used when working with access database
cn.Open()
cmd = New OleDbCommand("select * from Draw where Barcode= " + txtBarcode.Text, cn)
dr = cmd.ExecuteReader
While dr.Read()
txtHNumber.Text = dr(1)

' loading data into TextBoxes by column index
End While
Catch
End Try
dr.Close()
cn.Close()

If someone is able to give me an answer as to why it crashes with one data type in the access database for the Barcode field and not the other it would be appreciated
 
Text literals need to be quoted in SQL code:
VB.NET:
cmd = New OleDbCommand("select * from Draw where Barcode= '" & txtBarcode.Text & "'", cn)
That said, using string concatenation to insert variables into SQL code like that is a bad idea for several reasons. To learn how to do it properly, follow the Blog link in my signature and check out my post on ADO.NET parameters.
 
Back
Top