Chapter Twenty Four – SQL Server
Visual Basic .NET
When you close the programme down and then reopen it, however, the record will be back
This is because you’re not doing anything to the underlying database – DataTables and Datasets
are disconnected from the database. So we need to write some code to reconnect, and then
Add a button to your form. Change the Name property to btnUpdate. Change the Text property
to Update Changes. Double click your button to open up its code stub.
The button, then, needs to do two things: issue the Update command against the underlying
database, and refresh the connection.
Add the following two lines to your button code:
data_adapter.Update( CType(binding_source.DataSource, DataTable) )
Get_DGV_Data( data_adapter.SelectCommand.CommandText )
The first line is the one that updates the database. Its done simply by typing the word Update
after the name of your Data Adapter. In between the round brackets, though, you have to tell it
what it is you’re updating. Because we have a binding source object, we have to specify the
However, the Data Adapter doesn’t know what to do with this, so you have to convert it to a
Type that it does understand – a DataTable:
CType( binding_source.DataSource, DataTable )
The CType part means “Convert to Type”. In between the round brackets, you add what it is
you’re trying to convert. After a comma, you add the Type you want to convert to, a DataTable
for us. So we’re saying, “Convert the DataSource of the BindingSource object to a DataTable”.
The second line calls our Get_DGV_Data( ) Sub again. Notice how we’re getting the SQL
So the Data Adapter has a SelectCommand property. This in turn has a CommandText
property. The CommandText is a SQL Command, and it already knows what to do – get all the
records from the database again.
Run your programme and try it out. You should now be able to add records, close the
programme down, and still see them there. You should also be able to delete a row. When you
click your Update Changes button, the row will be deleted from the database as well as the Data