meljun cortes vb.net handout ado.net
TRANSCRIPT
Visual Basic .NET Programming
ADO.NET * Property of STI Page 1 of 15
TOPIC TITLE: ADO.NET Specific Objectives: At the end of the topic session, the students are expected to: Cognitive:
1. Explain the DataSet object 2. Explain how to populate DataSets 3. Explain the relationship in DataSets 4. Explain how to create Constraints. 5. Explain how to update data in a DataSet. 6. Explain data binding.
Affective:
1. Listen to others with respect. 2. Participate in class discussions actively.
MATERIALS/EQUIPMENT:
o topic slides o OHP
TOPIC PREPARATION:
o Have the students research on the following: � DataSet objects � Data Binding
o It is imperative for the instructor to incorporate various kinds of teaching strategies while discussing the suggested topics. The instructor may use the suggested learning activities below to facilitate a thorough and creative discussion of the topic.
o Prepare the slides to be presented in the class.
TOPIC PRESENTATION: The topic will revolve around the overview of classes and objects. This will be the suggested flow of discussion for the course topic:
1. Introduce to the students the topics to be covered in this session.
2. Explain the DataSet object. 3. Explain how to populate DataSets. 4. Explain the relationship in DataSets. 5. Explain how to create Constraints. 6. Explain how to update data in a DataSet. 7. Explain data binding,
Visual Basic .NET Programming
ADO.NET * Property of STI Page 2 of 15
The DataSet Object Page 1 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 1 of 26
DataSetDataSetDataSetDataSetObjectObjectObjectObject
� a disconnected, memory resident cache of data
� reads the database and creates an in-
memory copy of that part of that database
that the program needs
� contains DataTables, DataRelation and
Constraints objects
The DataSet Object
The main new feature in ADO.NET is provided by the DataSet object. This object is a disconnected, memory resident cache of data that reads the database and creates an in-memory copy of that part of that database that the program needs. After the data set is created, there is no longer an active connection to the database. Thus, it improves performance because the only time that the program has to connect to with the database server is when reading or writing from the database. It contains DataTables, DataRelation and Constraints objects.
The DataTable object consists of the Columns collection and Rows
collection. These are used to manipulate the fields and query the properties. The DataRelation contains definitions of all the
relationships that exist between the DataTable and DataSet. [The DataSet Object, Page 1 of 26]
Populating DataSets Page 2 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 2 of 26
PopulatingPopulatingPopulatingPopulatingDataSetsDataSetsDataSetsDataSets
� done at runtime
� use DataAdapter to access data
� Example:
Private conServer As
SqlClient.SqlConnection
Public Sub Form1_Load(ByVal
sender As System.Object,
ByVal e As System.EventArgs)
Handles MyBase.Load
conserver = New
SqlClient.SqlConnection()
Dim strConnection As String =
“Integrated Security=True;Data
Source=Localhost;Initial
Catalog=Books;”
conServer.ConnectionString =
strConnection
conserver.Open()
End Sub
Populating DataSets Page 3 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 3 of 26
PopulatingPopulatingPopulatingPopulatingDataSetsDataSetsDataSetsDataSets
� Example: (con’t)
Private Sub Button1_Click ByVal sender
As System.Object, ByVal e As
System.EventArgs) Handles
Button1.Click
Dim adaptSQL As
SqlClient.SqlDataAdapter(“Select
count(*) from Catalogue”,
conserver)
‘the code that will fill the DataSet
Dim datBooks As New DataSet()
adaptSQL.Fill(datBooks, “MyTable”)
‘manipulate data locally using
DataSet
adaptSQL.Update(datBooks, “MyTable”)
End Sub
Populating DataSets
Populating a DataSet is done at runtime. The DataAdapter is used
to access data stored in the database and store the data in DataTable
objects within a DataSet in the application.
The sample codes shown below demonstrate how to populate
DataSets. This example is similar to the code shown in the ‘Populating
a DataTable’ in the previous topic. The DataTable to be populated is
called “MyTable” with data from a database. Private conServer As SqlClient.SqlConnection
Public Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
conserver = New SqlClient.SqlConnection()
Dim strConnection As String = “Integrated
Security=True;Data Source=Localhost;Initial
Catalog=Books;”
conServer.ConnectionString = strConnection
conserver.Open()
End Sub
Private Sub Button1_Click ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim adaptSQL As SqlClient.SqlDataAdapter(“Select
count(*) from Catalogue”, conserver)
‘the code that will fill the DataSet
Dim datBooks As New DataSet()
adaptSQL.Fill(datBooks, “MyTable”)
‘manipulate data locally using DataSet
adaptSQL.Update(datBooks, “MyTable”)
End Sub
[Populating DataSets, Pages 2-3 of 26]
Visual Basic .NET Programming
ADO.NET * Property of STI Page 3 of 15
Relationships in DataSet Page 4 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 4 of 26
Relationships Relationships Relationships Relationships inininin DataSetDataSetDataSetDataSet
� DataRelation object
� allows tables to provide relationship with each
other
� contains an array of DataColumn objects that
define the parent column, primary key and child
column or foreign key in the relationship
� Example:
Private Sub Button1_Click ByVal sender As
System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim adaptSQL As SqlClient.SqlDataAdapter
Dim datBooks As New DataSet()
adaptSql = New
SqlClient.SqlDataAdapter(“Select ISDN,
title, author, publisher from
Catalogue”, conServer)
adaptSQL.Fill(datBooks, “MyTable1”)
adaptSql = New
SqlClient.SqlDataAdapter(“Select ISDN,
name, address from Publisher”,
conServer)
adaptSQL.Fill(datBooks, “MyTable2”)
Relationships in DataSet Page 5 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 5 of 26
Relationships in Relationships in Relationships in Relationships in DataSetDataSetDataSetDataSet
� Example: (con’t)
‘the code that provides the
relationship
Dim relBooksTitile As New
DataRelation(“BooksTitles”,
datBooks.Tables(“MyTable1”).Columns(
“ISDN”),
datBooks.Tables(“MyTable2”).Columns(
“ISDN”))
datBooks.Relations.Add(relBooksTitle)
End Sub
Relationships in DataSet
The DataRelation object allows tables to provide relationship with
each other. Each DataRelation object contains an array of
DataColumn objects that define the parent column or columns, primary key and child column or columns or foreign key in the relationship. An example is shown below, which demonstrates how to establish relationship between objects. The relationship is defined by the use of
the DataRelation object. See the line of codes that provides the relationship below.
Private conServer As SqlClient.SqlConnection
Public Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
conServer = New SqlClient.SqlConnection()
Dim strConnection As String = “Integrated
Security=True;Data Source=Localhost;Initial
Catalog=Books;”
conServer.ConnectionString = strConnection
conServer.Open()
End Sub
Private Sub Button1_Click ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim adaptSQL As SqlClient.SqlDataAdapter
‘the code that will fill the DataSet
Dim datBooks As New DataSet()
adaptSql = New SqlClient.SqlDataAdapter(“Select
ISDN, title, author, publisher from Catalogue”,
conServer)
adaptSQL.Fill(datBooks, “MyTable1”)
adaptSql = New SqlClient.SqlDataAdapter(“Select
ISDN, name, address from Publisher”, conServer)
adaptSQL.Fill(datBooks, “MyTable2”)
‘the code that provides the relationship
Dim relBooksTitile As New
DataRelation(“BooksTitles”,
datBooks.Tables(“MyTable1”).Columns(“ISDN”),
datBooks.Tables(“MyTable2”).Columns(“ISDN”))
datBooks.Relations.Add(relBooksTitle)
End Sub
[Relationships in DataSet, Pages 4-5 of 26]
Visual Basic .NET Programming
ADO.NET * Property of STI Page 4 of 15
Accessing Related Data Pages 4 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 6 of 26
AccessingAccessingAccessingAccessingRelated DataRelated DataRelated DataRelated Data
� GetChildRows method
� used to access related records in a
different table
� Example
Dim BookRow, PubRow As DataRow
Dim TitleRows() As DataRow ‘ Array
of DataRow objects
BookRow =
datBooks.Tables(“MyTable1”).Rows
(0)
TitleRows =
BookRow.GetChildRows(“BooksTitle
s”)
For Each PubRow In TitleRows
ListBox1.Items.Add(PubRow(“title
”).ToString)
Next
Accessing Related Data
The GetChildRows method of a DataRow object is used to access related records in a different table. This method returns an array of
DataRow objects. An example on how to access related records is shown below. The ListBox control is populated with data from an array
of DataRow objects. Dim BookRow, PubRow As DataRow
Dim TitleRows() As DataRow ‘ Array of DataRow objects
BookRow = datBooks.Tables(“MyTable1”).Rows(0)
TitleRows = BookRow.GetChildRows(“BooksTitles”)
For Each PubRow In TitleRows
ListBox1.Items.Add(PubRow(“title”).ToString)
Next
[Accessing Related Data, Page 6 of 26]
Creating Constraints Page 7 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 7 of 26
Creating Creating Creating Creating ConstraintsConstraintsConstraintsConstraints
� Constraint
� a rule used to maintain the integrity of the
data in the DataTable
� Types of constraint classes to DataColumns:
� ForeignKeyConstraint
� UniqueConstraint
� ForeignKeyConstraint
� controls what happens to a child row when a
parent row is updated or deleted
Does not affect related rows.None
Sets related values to their
defaults.
SetDefault
Sets related values to DB Null.SetNull
Deletes or updates any child
records based on the parent record.
Cascade
Creating Constraints Page 8 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 8 of 26
Creating Creating Creating Creating ConstraintsConstraintsConstraintsConstraints
� ForeignKeyConstraint Example:
Dim colParent As DataColumn
Dim colChild As DataColumn
Dim fkcBooksTitles As
ForeignKeyConstraint
colParent =
datBooks.Tables(“MyTable1”).Columns(
“ISDN”)
colChild =
datBooks.Tables(“MyTable2”).Columns(
“ISDN”)
fkcBooksTitles = New
ForeignKeyConstraint(“BooksTitlesFKC
onstraint”, colParent, colChild)
fkcBooksTitles.DeleteRule =
Rule.SetNull
fkcBooksTitles.UpdateRule =
Rule.Cascade
datBooks.Tables(“titles”).Constraints.A
dd(fkcBooksTtiles)
datBooks.EnforceConstraints = True
Creating Constraints A constraint is a rule used to maintain the integrity of the data in the
DataTable. For example, when you delete a value that is used in one
or more related tables, a ForeignKeyConstraint determines whether the values in the related tables are also deleted, set to null values, set to
default values, or whether no action occurs. A UniqueConstraint, on the other hand, simply ensures that all values within a particular table are unique.
There are two types of constraint classes to DataColumns that can be
used to create new constraints namely ForeignKeyConstraint and
UniqueConstraint.
The ForeignKeyConstraint object controls what happens to a child row when a parent row is updated or deleted. The following table shows
the values for the DeleteRule and UpdateRule properties of the
ForeignKeyConstraint. Cascade Deletes or updates any child records
based on the parent record. SetNull Sets related values to DB Null. SetDefault Sets related values to their defaults. None Does not affect related rows.
The example shown below shows how to create and define constraints.
An instance of the ForeignKeyConstraint object is created named
fkcBooksTitles. Then, rules are applied to the fkcBooksTitles.
Next, the constraint is added to the table using the Add method of the
Constraints object.
Dim colParent As DataColumn
Dim colChild As DataColumn
Dim fkcBooksTitles As ForeignKeyConstraint
colParent =
datBooks.Tables(“MyTable1”).Columns(“ISDN”)
colChild =
datBooks.Tables(“MyTable2”).Columns(“ISDN”)
Visual Basic .NET Programming
ADO.NET * Property of STI Page 5 of 15
Creating Constraints Page 9 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 9 of 26
Creating Creating Creating Creating ConstraintsConstraintsConstraintsConstraints
� UniqueConstraint
� can be added to one column or to an array
of columns
� checks if the values in the columns are
unique
� UniqueConstraint Example
Dim ucTitles As New
UniqueConstraint(“UniqueTitles”,
datBooks.Tables(“titles”).Column
s(“title”))
datBooks.EnforceConstraints = True
fkcBooksTitles = New
ForeignKeyConstraint(“BooksTitlesFKConstraint”,
colParent, colChild)
fkcBooksTitles.DeleteRule = Rule.SetNull
fkcBooksTitles.UpdateRule = Rule.Cascade
datBooks.Tables(“titles”).Constraints.Add(fkcBooksTti
les)
datBooks.EnforceConstraints = True
On the other hand, the UniqueConstraint can be added to one column or to an array of columns. It checks if the values in the columns are unique. An example is shown below: Dim ucTitles As New UniqueConstraint(“UniqueTitles”,
datBooks.Tables(“titles”).Columns(“title”))
datBooks.EnforceConstraints = True
[Creating Constraints, Pages 7-9 of 26]
Using Existing Constraints Page 10 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 10 of 26
Using Existing Using Existing Using Existing Using Existing ConstraintsConstraintsConstraintsConstraints
� FillSchema method
� used to copy constraint information into a
DataSet
� Example:
adaptSQL = New
SqlClient.SqlDataAdapter(“Select
ISDN, title, author, publisher
from Catalogue”, conServer)
adaptSQL.FillSchema(datBooks,
schematype.Source, “Titles”)
adaptSQL.Fill(datBooks, “Titles”)
‘edit some data
adaptSQL.Fill(datBooks, “Titles”)
Using Existing Constraints
The FillSchema method is used to copy constraint information into a DataSet.
adaptSQL = New SqlClient.SqlDataAdapter(“Select ISDN, title, author, publisher from Catalogue”,
conServer)
adaptSQL.FillSchema(datBooks, schematype.Source,
“Titles”)
adaptSQL.Fill(datBooks, “Titles”)
‘edit some data
adaptSQL.Fill(datBooks, “Titles”)
[Using Existing Constraints, Page 10 of 26]
Updating Data in the DataSet Page 11 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 11 of 26
Updating Data Updating Data Updating Data Updating Data in the in the in the in the DataSetDataSetDataSetDataSet
� Adding Rows
� instantiate DataRow object by issuing the
NewRow method of the DataTable
� populate the columns with data
� call the Add method of the DataRows
collection passing the DataRow object
� Example:
Dim newDataRow As DataRow =
datBooks.Tables(“Titles”).NewRow
newDataRow(“title”) = “New York”
newDataRow(“type”) = “business”
datBooks.Tables(“Titles”.Rows.Add(n
ewDataRow)
Updating Data in the DataSet There are three operations that you can do in a DataSet namely add, update and delete data. Adding Rows The following steps are used to add new rows to a table:
1. Instantiate DataRow object by issuing the NewRow method of
the DataTable.
2. Populate the columns with data.
3. Call the Add method of the DataRows collection passing the
DataRow object. The example below demonstrates the steps discussed above in adding rows to a table. Dim newDataRow As DataRow =
Visual Basic .NET Programming
ADO.NET * Property of STI Page 6 of 15
Updating Data in the DataSet Page 12 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 12 of 26
Updating Data Updating Data Updating Data Updating Data in the in the in the in the DataSetDataSetDataSetDataSet
� Editing existing rows
� Call the BeginEdit method of the row.
� Change the data in the columns.
� Call the EndEdit or CancelEdit to
accept or reject the changes.
� Example:
Dim editDataRow As DataRow =
datBooks.Tables(“Titles”).Rows(0
)
editDataRow.BeginEdit()
editdataRow(“Title”) =
editDataRow(“Title”).ToString &
“ 1”
editDataRow.EndEdit()
Updating Data in the DataSet Page 13 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 13 of 26
Updating Data Updating Data Updating Data Updating Data in the in the in the in the DataSetDataSetDataSetDataSet
� Deleting Data
� Remove method
� Delete method
� Remove method Example
Dim delRow As DataRow =
datBooks.Tables(“Titles”).Rows(0
)
datBooks.Tables(“Titles”).Rows.Rem
ove(delRow)
� Delete method Example
Dim delRow As DataRow =
datBooks.Tables(“Titles”).Rows(0)
datBooks.Tables(“Titles”).Rows.Delete(delRo
w)
Updating Data in the DataSet Page 14 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 14 of 26
Updating Data Updating Data Updating Data Updating Data in the in the in the in the DataSetDataSetDataSetDataSet
� To commit deletion invoke AcceptChangesof the DataSet:
� datBooks.AcceptChanges()
� To undo deletion invoke RejectChanges of the DataSet:
� datBooks.RejectChanges()
datBooks.Tables(“Titles”).NewRow
newDataRow(“title”) = “New York”
newDataRow(“type”) = “business”
datBooks.Tables(“Titles”.Rows.Add(newDataRow)
Editing Rows The following steps are used to edit existing rows in a table:
1. Call the BeginEdit method of the row. 2. Change the data in the columns.
3. Call the EndEdit or CancelEdit to accept or reject the
changes. The example below demonstrates the steps discussed above in editing existing rows in a table. Dim editDataRow As DataRow =
datBooks.Tables(“Titles”).Rows(0)
editDataRow.BeginEdit()
editdataRow(“Title”) = editDataRow(“Title”).ToString
& “ 1”
editDataRow.EndEdit()
Deleting Data There are two ways to delete a row:
• Remove method
• Delete method
Example of Remove method is shown below. The Remove method of
the DataRow collection deletes permanently the row from the DataSet (datBooks as instance). Dim delRow As DataRow =
datBooks.Tables(“Titles”).Rows(0)
datBooks.Tables(“Titles”).Rows.Remove(delRow)
Example of Delete method is shown below. The Delete method only
marks the row for deletion in the DataSet (datBooks as instance). To
delete it permanently, the AcceptChanges method is called or to undo
the deletion, the RejectChanges method is invoked.
Dim delRow As DataRow =
datBooks.Tables(“Titles”).Rows(0)
datBooks.Tables(“Titles”).Rows.Delete(delRow)
To commit deletion invoke AcceptChanges of the DataSet: � datBooks.AcceptChanges()
To undo deletion invoke RejectChanges of the DataSet:
� datBooks.RejectChanges()
[Updating Data in the DataSet, Pages 11-14 of 26]
Visual Basic .NET Programming
ADO.NET * Property of STI Page 7 of 15
Designing DataSets Page 15 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 15 of 26
Designing Designing Designing Designing DataSetsDataSetsDataSetsDataSets
� Connection Wizard
� Tools > Connect to Database
� click the Change button to select the data
source
Designing DataSets There are a number of designers available in VB.Net to simplify the process of DataSet creation. These include the Connection Wizard and DataAdapter Configuration Wizard. Connection Wizard The Connection Wizard is called when you select the Connect to Database from the Tools menu. The Connection wizard start page is shown below:
To create a connection using the Connection Wizard, perform the following:
1. On the Tools menu, select Connect to Database. The Add Connection dialog box appears.
2. Click the Change button to select the data source. A new window will appear as shown below.
3. Select the data source to be used. For this demonstration, select Microsoft ODBC Data Source then click OK.
Visual Basic .NET Programming
ADO.NET * Property of STI Page 8 of 15
Designing DataSets Page 16 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 16 of 26
Designing Designing Designing Designing DataSetsDataSetsDataSetsDataSets
� select a data source then click OK
� on the Data source specification section, click
the Use user or system data source namethen select the MS Access Database
� click OK. Select the Access database file and
then click OK
� open the Server Explorer panel to see the
connection that appears under the Data
Connections
Designing DataSets Page 17 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 17 of 26
Designing Designing Designing Designing DataSetsDataSetsDataSetsDataSets
� DataAdapter Configuration Wizard
� can be used with an existing database
connection
� Adding DataAdapter to Toolbox
� right-click Data from the Toolbox then
click Choose Items
� tick on a data adapter
• (i.e. OleDbDataAdapter)
� click OK
4. Back to the Add Connection page, on the Data source
specification section, click the Use user or system data source name then select the MS Access Database. You use this if you want to select the database using the file dialog control.
NOTE: The view of the Add Connection dialog box varies depending on the selected Data Source in the Change Data Source dialog box. 5. Click OK. A file dialog box appears. Select the Access
database file and then click OK. 6. You are now connected to the database. Open the Server
Explorer panel to see the connection that appears under the Data Connections.
DataAdapter Configuration Wizard The DataAdapter Configuration wizard can be used with an existing database connection. The wizard can be initiated by adding a SqlDataAdapter or OleDbDataAdapter from the Toolbox to a form at design time. It requires the following information:
• Connection name
• Query type
• Details of the query In previous versions of Microsoft Visual Studio (2002 and 2003), the Toolbox was equipped with various data adapters. However, It was removed in the 2005 version. If you want to visually create a data adapter, you must manually add it to the Toolbox. To add data adapter to Toolbox:
1. Right-click the Data section of the Toolbox and click Choose Items. The Choose Toolbox Items dialog box appears.
Visual Basic .NET Programming
ADO.NET * Property of STI Page 9 of 15
2. In the .NET Framework Component tab, scroll down and put a
check mark on a data adapter, example the OleDbDataAdapter. 3. Click OK. The selected adapter is added to the Toolbox.
[Designing DataSets, Pages 15-17 of 26]
Data Binding in Windows Forms Page 18 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 18 of 26
Data Binding in Data Binding in Data Binding in Data Binding in Windows FormsWindows FormsWindows FormsWindows Forms
� Data binding
� used to customize the appearance of the
forms
� Types of binding
� Simple Binding
• used to link a control to a single field in a
DataSet
� Complex Binding
• used to link multiple fields in a DataSet
Data Binding in Windows Forms Page 19 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 19 of 26
Data Binding in Data Binding in Data Binding in Data Binding in Windows FormsWindows FormsWindows FormsWindows Forms
� Simple Binding Example:Private conServer As SqlClient.SqlConnection
Public Sub Form1_Load(ByVal sender As
System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
conserver = New SqlClient.SqlConnection()
Dim strConnection As String = “Integrated
Security=True;Data
Source=Localhost;Initial Catalog=Books;”
conServer.ConnectionString = strConnection
conserver.Open()
End Sub
Private Sub Button1_Click ByVal sender As
System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim adaptSQL As
SqlClient.SqlDataAdapter(“Select title,
author from Catalogue”, conserver)
‘the code that will fill the DataSet
Dim datBooks As New DataSet()
adaptSQL.Fill(datBooks, “Catalogue”)
TextBox1.DataBindings.Add(“Text”,
datBooks.Tables(“Catalogue”), “title”)
TextBox2.DataBindings.Add(“Text”,
datBooks.Tables(“Catalogue”), “author”)
End Sub
Data Binding in Windows Forms Data binding is used if you want to customize the appearance of the forms. There are two types of binding namely simple binding and complex binding. These two can be implemented at design time either by using the Properties window or at runtime by using code. Simple Binding Simple binding is used to link a control to a single field in a DataSet. An example is simple binding in a TextBox control, using the DataBindings property; specify which DataSet and which field of a table to bind to which property. The following example shows how to bind data to a TextBox control. Private conServer As SqlClient.SqlConnection
Public Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
conserver = New SqlClient.SqlConnection()
Dim strConnection As String = “Integrated
Security=True;Data Source=Localhost;Initial
Catalog=Books;”
conServer.ConnectionString = strConnection
conserver.Open()
End Sub
Private Sub Button1_Click ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim adaptSQL As SqlClient.SqlDataAdapter(“Select
title, author from Catalogue”, conserver)
‘the code that will fill the DataSet
Dim datBooks As New DataSet()
adaptSQL.Fill(datBooks, “Catalogue”)
Visual Basic .NET Programming
ADO.NET * Property of STI Page 10 of 15
Data Binding in Windows Forms Page 20 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 20 of 26
Data Binding in Data Binding in Data Binding in Data Binding in Windows FormsWindows FormsWindows FormsWindows Forms
� Complex Binding Example:
Private conServer As SqlClient.SqlConnection
Public Sub Form1_Load(ByVal sender As
System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
conserver = New SqlClient.SqlConnection()
Dim strConnection As String = “Integrated
Security=True;Data
Source=Localhost;Initial Catalog=Books;”
conServer.ConnectionString = strConnection
conserver.Open()
End Sub
Private Sub Button1_Click ByVal sender As
System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim adaptSQL As
SqlClient.SqlDataAdapter(“Select title,
author from Catalogue”, conserver)
‘the code that will fill the DataSet
Dim datBooks As New DataSet()
adaptSQL.Fill(datBooks, “Catalogue”)
DataGrid1.DataSource =
datBooks.Tables(“Catalogue”)
End Sub
TextBox1.DataBindings.Add(“Text”,
datBooks.Tables(“Catalogue”), “title”)
TextBox2.DataBindings.Add(“Text”,
datBooks.Tables(“Catalogue”), “author”)
End Sub
Complex Binding Complex binding is used to link multiple fields in a DataSet. For example, complex binding is used for DataGrid control. This control has a DataSource property that allows you to specify the table to be used. The following example shows how to bind data to a DataGrid control. Private conServer As SqlClient.SqlConnection
Public Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
conserver = New SqlClient.SqlConnection()
Dim strConnection As String = “Integrated
Security=True;Data Source=Localhost;Initial
Catalog=Books;”
conServer.ConnectionString = strConnection
conserver.Open()
End Sub
Private Sub Button1_Click ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim adaptSQL As SqlClient.SqlDataAdapter(“Select
title, author from Catalogue”, conserver)
‘the code that will fill the DataSet
Dim datBooks As New DataSet()
adaptSQL.Fill(datBooks, “Catalogue”)
DataGrid1.DataSource = datBooks.Tables(“Catalogue”)
End Sub
[Data Binding in Windows Forms, Pages 18-20 of 26]
Demonstration: How to Create a Data Source Demonstrate the following to your students. Before you start the demonstration, create a MS Access database file named StudentDB. Create a table named Student that has the following fields:
• fname
• lname
• age
• course
• address
Save the database file and open the VS 2005 for the demo.
1. To begin, go to File, New Project and name the project as MyDataSource.
2. Click the OK button. VS .Net displays the first form named
Visual Basic .NET Programming
ADO.NET * Property of STI Page 11 of 15
Demonstration: How to Create a Data Source Page 21 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 21 of 26
Demonstration: How to Demonstration: How to Demonstration: How to Demonstration: How to Create a Data SourceCreate a Data SourceCreate a Data SourceCreate a Data Source
� File > New Project and name it as
MyDataSource then click OK
� select the ToolBox tab
� select the OleDbDataAdapter from the ToolBox and drop it onto the form
� click New Connection
Demonstration: How to Create a Data Source Page 22 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 22 of 26
Demonstration: How to Demonstration: How to Demonstration: How to Demonstration: How to Create a Data SourceCreate a Data SourceCreate a Data SourceCreate a Data Source
� click the Change button
� select Microsoft Access Database File then click OK
Form1.vb. 3. Click once anywhere on the form and then select the ToolBox
tab on the left of the design window. 4. Next, select the OleDbDataAdapter from the ToolBox and drop
it onto the form. Once you release it, it does not actually sit on top of the form but instead, it positions itself onto the component tray. At this point, the Data Adapter Configuration Wizard appears.
NOTE: If you already have an existing connection to the database that you want to use then select the database from the dropdown list and skip steps 5 – 8.
5. Click New Connection. The Add Connection dialog box
appears. 6. In the Add Connection page, click the Change button to change
the data source. A new window will appear as shown below.
7. Select the Microsoft Access Database File then click OK. You are back to the Add Connection dialog box.
Visual Basic .NET Programming
ADO.NET * Property of STI Page 12 of 15
Demonstration: How to Create a Data Source Page 23 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 23 of 26
Demonstration: How to Demonstration: How to Demonstration: How to Demonstration: How to Create a Data SourceCreate a Data SourceCreate a Data SourceCreate a Data Source
� click the Browse button to locate
StudentDB access database then click OK
� click Next
� select Use SQL Statements then click Next
Demonstration: How to Create a Data Source Page 24 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 24 of 26
Demonstration: How to Demonstration: How to Demonstration: How to Demonstration: How to Create a Data SourceCreate a Data SourceCreate a Data SourceCreate a Data Source
� click the Query Builder button
� select the Student table then click Addand Close button
8. Click the Browse button on the Database file name section and locate StudentDB access database. Click OK.
9. Now click Next to advance to the next screen of the wizard where you can use SQL statements, or existing stored procedures, or create new stored procedures.
10. Select Use SQL Statements radio button and click the Next
button. See image on the next page.
Visual Basic .NET Programming
ADO.NET * Property of STI Page 13 of 15
Demonstration: How to Create a Data Source Page 25 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 25 of 26
Demonstration: How to Demonstration: How to Demonstration: How to Demonstration: How to Create a Data SourceCreate a Data SourceCreate a Data SourceCreate a Data Source
� tick the (All Columns) checkbox
� click the OK button to save and close the window
SELECT student.*
FROM student
� click Next then the Finish button
� right-click the OleDbDataAdapter1 and
select Generate DataSet then click the OK button
� right-click on the OleDbDataAdapter1again then choose Preview Data
Demonstration: How to Create a Data Source Page 26 of 26
ADO.NET
Visual Basic .NET Programming
* Property of STIPage 26 of 26
Demonstration: How to Demonstration: How to Demonstration: How to Demonstration: How to Create a Data SourceCreate a Data SourceCreate a Data SourceCreate a Data Source
� click the Preview button to view data in then click the Close button
� OleDbDataAdapter, OleDbConnection, and
dataset are now created. This new
dataset can be used in any .Net control of your choice
11. Click the Query Builder button to create your query.
12. Select the Student table from the Add Table dialog box and
click the Add button and then the Close button. The Student table must appear in the Query Builder window.
Visual Basic .NET Programming
ADO.NET * Property of STI Page 14 of 15
13. Tick the (All Columns) checkbox in the Student table. Notice
that a query statement appears in the mid-section of the Query Builder window.
14. Click the OK button to save and close the window. You are once again back at the wizard and now you will see the query statement generated in the Query Builder.
SELECT student.*
FROM student
15. Now, click the Next button to display the wizard result and then
click the Finish button to close the wizard. Notice that in the design view of Form1, specifically in the component tray, OleDbConnection1 appears.
16. Right-click the OleDbDataAdapter1 on the component tray and select Generate DataSet. Leave the default settings as is and click the OK button. DataSet1 appears in the component tray.
17. Right-click on the OleDbDataAdapter1 again but this time, choose Preview Data. The Preview Data dialog box appears.
18. Click the Preview button. The data in Student table now
appears in the Preview Data dialog box. Click the Close button. 19. You have just created your first OleDbDataAdapter,
OleDbConnection, and dataset. You could now use this new dataset in any .Net control of your choice.
[Demonstration: How to Create a Data Source, Page 26 of 26]
EVALUATION/GENERALIZATION:
o DataSet class was developed to help you create and manage any type of list-based application.
o The DataTable object consists of the Columns collection and Rows collection which are used to manipulate the fields and query the properties.
o A data adapter is an object that takes data from a database, reads that data, and "fills" a DataSet object with that data.
o The DataRelation object provides relationship in each tables. o The DataRow object has GetChildRows method that is used to
access related records in a different table. o A constraint is a rule used to maintain the integrity of the data in
the DataTable. o There are three operations that you can do in a DataSet namely
Visual Basic .NET Programming
ADO.NET * Property of STI Page 15 of 15
add, update and delete data.
o Simple binding is used to link a control to a single field in a DataSet while complex binding is used to link multiple fields in a DataSet.
REFERENCES:
� Microsoft Official Course, (2002), 2373B: Programming with
Microsoft Visual Basic .NET, Microsoft Corporation � Holzner, Steven, (2003), Sams teach yourself Microsoft Visual
Basic.Net 2003 in 21 days, USA, Sams Publishing � Liberty, Jesse, (2003), Learning Visual Basic .NET, USA,
O'Reilly & Associates, Inc