Vb 10 nullreference exception
i got this code from the net , but i can't make this code work on the system i am programming so, i used the same codes to another system and it worked, when i tried using it to my system, it failed, so i started a new program and it still fails... what is wrong with my program? here is a sample of the code:
Public Class Form2
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim inc As Integer
Dim max As Integer
Private Sub AllRecordsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
dbProvider = "PROVIDER = Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = C:\Users\Josh\Documents\enrollment.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM Personal"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "enrollment")
max = ds.Tab开发者_如何学JAVAles("enrollment").Rows.Count
inc = -1
con.Close()
Private Sub Sve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Sve.Click
If inc <> -1 Then
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsnewrow As DataRow
dsnewrow = ds.Tables("enrollment").NewRow()
dsnewrow.Item("LastName") = TextLast.Text
ds.Tables("enrollment").Rows.Add(dsnewrow)
da.Update(ds, "enrollment")
MsgBox("Saved!")
End If
End Sub
whenever i run the program, it compiles, but when i click the commit button, this message appears "NullReference Exception was unhandled Object reference not set to an instance of an objects" and it points to .NewRow
If I read right, you're getting the exception on this line:
dsnewrow = ds.Tables("enrollment").NewRow()
This means that either ds
is null
(unlikely since it's initialized), or that the table "enrollment" doesn't exist in the dataset.
However, it's very hard to answer your question well since you've not posted all of the code (the end of the first sub is missing, which suggests more code is probably missing too).
Have you clicked your toolstripmenuitem before you click commit? It looks like that's responsible for populating the dataset.
Mostly, though, I'd advise you learn to understand the code that you've copied better before you start posting questions about it...
精彩评论