|
|
Title | Bind simple controls to a database in VB .NET |
Keywords | database, ADO.NET, VB .NET, bound controls, data binding |
Categories | Database, VB.NET, Software Engineering |
|
|
Add database connection, data adapter, and DataSet objects to the form:
- Database Connection:
- Open the form designer. On the Toolbox, click the Data tab. Double click the OldDbConnection tool.
- Select the new connection object. In the Properties window, click on the ConnectionString property. Click the dropdown to the right and select . Use the resulting Data Link Properties dialog to specify the data provider and database.
- Data Adapter:
- Open the form designer. On the Toolbox, click the Data tab. Double click the OldDbDataAdapter tool.
- Work through Data Adapter Configuration Wizard.
- Select the database connection you just created.
- Select Use SQL Statements.
- Enter a SQL statement to select the records you want to display (or use the Query Builder to build a SQL statement).
- Click Finish.
- DataSet:
- Open the form designer. Open the Data menu and select Generate DataSet. Select the New option, enter a descriptive name for the generic DataSet type (e.g. DataSetEmployees), select the table(s) you want to use, leave the "Add this dataset to the designer" box checked, and click OK.
- Initially the new DataSet is named something like DataSetEmployees1. Change the name to something more consistent with your naming conventions such as dsEmployees.
For each control that you want to bind:
- Select the control.
- Open its DataBindings property (at the top in the Properties window).
- Select the Text property. Click the dropdown arrow on the right.
- Select the DataSet field you want to bind to this control.
At run time, you still need to load and save the database data. In the form's Load event handler, call the data adapter's Fill method to fill the DataSet. If the data adapter is daUsers and the DataSet is dsUsers, then you would use this code:
|
|
' Load the data.
daUsers.Fill(dsUsers)
|
|
In the form's Closing event handler, add code to save any changes made to the DataSet back into the database.
|
|
' Save any changes to the data.
daUsers.Update(dsUsers)
|
|
For more information on using databases with VB .NET, see my book Visual Basic .NET Database Programming.
|
|
|
|
|
|