DataSets and DataTables are disconnected from the datasource. That is, once you fill them, they no longer have a connection to the database. Any changes you make to the database
will not appear in the DataTable...because it is disconnected. Thus, this code:
cmd = New OleDbCommand("INSERT INTO Tools (ToolID, Description, Price, CompanyID, BoughtDate) VALUES ('" & varToolID & "', '" & varDesc & "', '" & varPrice & "', '" & varCompID & "', '" & varBDate & "')", cn)
cmd.ExecuteReader()
dgTools.Refresh()
will not update the datagrid with your new data. (On a quick side note...if you decide to continue with this method, you should use cmd.ExecuteNonQuery() to run your INSERT SQL, not the cmd.ExecuteReader() method.) If you want your changes to appear in the DataGrid, make the changes to the data in your
DataSet/DataTable, not directly to the database. Then you can save all the changes at once using the DataAdapter's Update method. This has the advantage of allowing users to cancel any changes, and all you the programmer have to do to handle this situation is...not save the changes.
Here's a quick example:
Dim da As OleDbDataAdapter
Dim dt As DataTable
'Assume a connection named 'cn' already exists
da = New OleDbDataAdapter("Select * from Tools", cn)
dt = New DataTable
da.Fill(dt)
DataGrid1.DataSource = dt
To add a new row to the DataTable:
Dim dr As DataRow
dr = dt.NewRow()
dr.Item("ToolID") = 2112
dr.Item("Description") = "Cool tool!"
dr.Item("Price") = "19.99"
dr.Item("CompanyID") = "999"
dr.Item("BoughtDate") = CType("8/2/2006", Date) 'use an actual date here...this is an example
dt.Rows.Add(dr)
The row you just added should show up in the DataGrid. However, it is not yet in the database. To save it to the database, you can do this:
dim cmd as OleDbCommand
cmd = New OleDbCommand("INSERT INTO Tools (ToolID, Description, Price, CompanyID, BoughtDate) VALUES (@ToolID, @Description, @Price, @CompanyID, @BoughtDate)", cn)
da.InsertCommand = cmd
With da.InsertCommand
.Parameters.Add("@ToolID", OleDbType.Int, 4, "ToolID")
.Parameters.Add("@Description", OleDbType.VarChar, 100, "Description")
.Parameters.Add("@Price", OleDbType.Currency, 4, "Price")
.Parameters.Add("@CompanyID", OleDbType.Int, 4, "CompanyID")
.Parameters.Add("@BoughtDate", OleDbType.Date, 4, "BoughtDate")
End With
Then, to actually insert the data:
da.Update(dt)
I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson
Arrrr, mateys! Ye needs ta be preparin' yerselves fer
Talk Like a Pirate Day! Ye has a choice: talk like a pira