Question error when coding to add in data to the ms access 2003 database in vb2005

clzanas

Member
Joined
Jul 15, 2009
Messages
16
Programming Experience
Beginner
Hi guys,

i have encountered this error Variable 'dsNewRow' is used before it has been assigned a value. A null reference exception could result at runtime when i click on the button to insert data into my ms access database.

here is my code :

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsNewRow As DataRow


da.Fill(ds, "db1")
txt1.Text = ds.Tables("db1").Rows(0).Item(1)

dsNewRow.Item("text") = txt1.Text
dsNewRow = ds.Tables("db1").NewRow()


ds.Tables("db1").Rows.Add(dsNewRow)

da.Update(ds, "db1")

MsgBox("New Record added to the Database")

End Sub

can anyone help me? thnks in advance!!

regards,

charles
 
It is not an error, it is a warning. This an issue that could result in error at runtime, and in this case will.
Declare the variable when you need it, and where it is assigned if possible, if not explicitly assign Nothing.
VB.NET:
Dim dsNewRow As DataRow = ds.Tables("db1").NewRow()
VB.NET:
Dim dsNewRow As DataRow = Nothing
The first option is what you would want to code here. And what happens now? You get an error at the same line as before
VB.NET:
dsNewRow.Item("text") = txt1.Text
error message is now:
Local variable 'dsNewRow' cannot be referred to before it is declared.
So you have to use this variable after is it declared, and after it has been assigned a DataRow instance.

You should also turn Option Strict on. This will give a new error at:
VB.NET:
txt1.Text = ds.Tables("db1").Rows(0).Item(1)
Option Strict On disallows implicit conversions from 'Object' to 'String'.
Item(index) here is type Object, it can contain any value of any type. Intellisense will here help you fix when you click the exclamation icon and select this replacement option:
VB.NET:
txt1.Text = CStr(ds.Tables("db1").Rows(0).Item(1))
I also recommend you start with the visual part of Visual Studio for database interaction, and get used to strongly typed datasets.
 
hi,

thnks for the reply. i can now update the ms access database.

but one question though:

May i know how do i do a compare of data in the ms access database?

that is if when i type something into the textbox on the form, it will actually check for any duplicate data before it insert into the database after i clicked on the update button.

So if there is a duplicate data in the same column. it will not insert in. Else it will insert into the ms access database.

thnks!!
 

Latest posts

Back
Top