The Table Adapter

The TableAdapter is an ADO.NET object that enables your application to communicate with a database. The table adapter lets you read to and write from a database. The TableAdapter's Fill method reads the data from the database and populates (fills) the dataset with the data. When the TableAdapter is created, code to fill the dataset with data is automatically added to the Startup event handler of the worksheet that contains the data-bound control, as shown in Listing 7.19.

Listing 7.19. Automatically filling a dataset

Private Sub Sheet1_Startup(ByVal sender As Object, ByVal e As _ System.EventArgs) Handles Me.Startup

'TODO: Delete this line of code to remove the 'default AutoFill for 'NorthwindDataSet.Customers'.

If Me.NeedsFill("NorthwindDataSet") Then Me.CustomersTableAdapter.Fill( _ Me.NorthwindDataSet.Customers)

End If End Sub

You can also use the table adapter to update the database with changes made to data in the data source. To do this, you must call the Update method of the TableAdapter, as shown in Listing 7.20.

Listing 7.20. Updating a database using a table adapter Me.CustomersTableAdapter.Update(NorthwindDataSet)

For controls that have simple data binding, such as the NamedRange control, you must first write code that updates the data source before calling the Update method of the TableAdapter. You can add this code in the Change event handler of the NamedRange control, as shown in Listing 7.21.

Listing 7.21. Updating a data source using the WriteValue method

Private Sub ContactNameNamedRange_Change(ByVal Target As _ Microsoft.Office.Interop.Excel.Range) Handles _ ContactNameNamedRange.Change

Me.ContactNameNamedRange.DataBindings( _ "Value").WriteValue()

End Sub

0 0

Post a comment