apii 4b db
TRANSCRIPT
-
7/25/2019 APII 4b DB
1/23
4/22/20
WORKING WITH DATABASES II
Using SQL Server DBs + Visual Basic
Objectives
To discuss:
Data-Related Objects including
SqlConnection
DataSetDataTables
DataAdapterDataReader
2
Objectives
Howto
connect to a database,
create and populate a DataTable,and
navigate therecordsin theDataTable.
Manipulatedata
edit records
add records
delete records
3
The DataGridViewControl
A convenient tool for displaying the contents ofdatabase tablesin rowsand columns.
Data bindingis used tolink database tables tocontrolsona programsforms.
Special objects called components provide thelinkingmechanism.
When you link a control to a database, a wizard
guidesyou throughtheprocess.We will use several data-related objects
4
-
7/25/2019 APII 4b DB
2/23
4/22/20
Data Objects5
Data-Related Objects
Datasource
Usually a database but can also be a textfile, Excel spreadsheet, XML file, or Webservice
Keeps track of the database name, location,username, password, and other connectioninformation.
Our data sources will be MSSQL Serverdatabase files
6
Data-Related Objects
TableAdapter
Pulls data from one or more database tables andcopiesit into a DataSet
Can
selectsome or all table rows,
add/ insert new rows,
deleterows, and
modify existing rows.UsesSQLqueries to retrieve and update database
tables.
7
Data-Related Objects
DataSet
In-memorycopyofdatapulled fromdatabase tables.Virtual container for your tables
Anapplicationcanmodify rowsin the DataSet,
add new rowsto the DataSet, and
delete rowsfromthe DataSet.
Changes to DataSets become permanent when anapplication uses a TableAdapter to write the
changesfromthe DataSet back to the database.DataSets can get data from more than
one datasourceand from more thanone TableAdapter.
8
-
7/25/2019 APII 4b DB
3/23
4/22/20
Data-Related Objects
DataTable
Table inside a DataSet
Holdsdata generated by a TableAdaptersSELECTquery.
Has a Rows collection that corresponds todatabase table rows.
You can loop through the Rows collection andinspect or modify individual column values withineachrow.E.g. loop through the rowsand add up a Totalscolumn.
9
Data-Related Objects
BindingSource
Optional.
Provides a link between a DataSetand oneor more controlsona form.
These controls are called data-boundcontrols.
If the user modifies the data in a control, theBindingSource can copy the changes to the
DataSet.
10
Conceptual View11
2-way Data Flow Between a Data Source and an Application Working with a Database12
-
7/25/2019 APII 4b DB
4/23
4/22/20
ADO.NET
ADO.NET (Active Data Objects)is the database technology forMicrosofts.NETplatform.
ADO.NETObjects:
Together, the following objectsretrieve data froma database:
ADO.NetsObjects
DataSet
DataTable
DataReader
ThetraditionalADOobjects
connection
command
13
ADO.NET Objects
ADO.NETObjects
DataSetand
DataTablethese are also optimised for moving disconnected setsof data across
the Internet and intranets, including throughfi rewalls:
a DataReaderresembles a forward-only, read-only RecordSet, found in the older
ADO
In ADO.NET, aDataReader is a broad category ofobjects used tosequentially read data from a data source.
Providesan eff icient way to access data.
14
ADO.NET Objects
Thetraditional ADO objects
connectionand
command
E.g.
myReader = myCommand.ExecuteReader();calls the ExecuteReadermethod on an instance of theCommand
object called myCommand in order to create a DataReadercalledmyReader.
The DataReaderretrievesdata (rowsf roma data source)
You use theReadmethod of theDataReaderobject to obtain arowfrom theresultsof the query
15
The ADO.Net Object Model16
-
7/25/2019 APII 4b DB
5/23
4/22/20
Some Data Objects & Their Purpose
SqlConnection
used to establish a connection to an SQL Server datasource.
DataSet
a memory-resident representationof data
There are many ways of working with a DataSet, suchasthroughDataTables.
DataTable holdsa result set of data for manipulation and navigation.
DataAdapter
isused to populatea DataReader.
17
MyVBDB18
MyVbDb
Create a newWindowsApplication named MyVbDb.
Right-click Form1.vb in the Solution Explorer window,choose Rename, and then change the name of thedefault formtoMainForm.vb.
Next, set the forms Text property to My DatabaseExample.
All the ADO.NET objects, except the DataTable, arepart of the System.Data namespace.
The DataTable is part ofSystem.Xml.
19
Remember this?Namespaces The Microsoft .NET Framework contains a largelibrary of classesthat
make it possible to write applications for desktop computing, mobileapplications, and the Web.
The classesare grouped by similarity into namespacesto make it easier tofind them.
A namespaceisa logical container that holdsclassesof similar types.
For example,
theSystem.Collections namespacecontains classes related to buildingcollections(arrays, l ists, dictionaries,sets).
The System.Windows.Forms namespace contains classes related tobuilding desktop applicationsfor Windows.
All the ADO.NET objects, except the DataTable, are part of theSystem.Datanamespace.
The DataTableispart ofSystem.Xml.OOP
20
-
7/25/2019 APII 4b DB
6/23
4/22/20
MyVbDb
All the ADO.NET objects, except the DataTable, are
part of theSystem.Datanamespace.
The DataTable is part of System.Xml.
We add referencesto bothnamespacesso that youcan use thenamespaceswithouthavingtotypethefullnamespacequalifier.
1. From the Menu bar, choose Project, MyVbDbPropertiesto display the Project Properties.
2. Click theReferences tab to display the activereferences for the project, as shown in the figure in
thenext slide.
21
MyVbDb22
12
MyVbDb
3. Inthe lower part of thispage isa checkbox list of imported namespaces.
Use the scrollbar f or this list box (not the main scrollbar for the page) tolocate and check
System.Data,
System.Data.SqlClient, and
System.Xml.
System.Data isprobably already checked and will appear toward thetop ofthelist.
If not, locateit and check it.
System.Data.SqlClient and System.Xml will most l ikely not be checked, andwillbe toward thebottomof the list.
4. Click SaveAll onthe toolbar.
5. Click theMainForm.vb [Design]tab to returnto the FormDesigner.
23
MyVbDbConnecting to a Database
To access the data in a database, you must firstestablishaconnection.
using anADO.NETconnectionobject.
Multiple connection objects are included in the .NETFramework, including:
TheOleDbConnection object(for working with OLE DBdata providers)
Object Linking and Embeddingis a proprietary technology developedby Microsoft that allows embedding and linking to documents andother objects
theSqlConnectionobject (for optimised access to MicrosoftSQLServer).
24
-
7/25/2019 APII 4b DB
7/23
4/22/20
MyVbDbConnecting to a Database
As we will connect to a Microsoft SQLDatabase, youll be using the SqlConnectionobject.
Example:
A statement suchas:
DimcnADONetConnectionAsNew SQLConnection()
Creates an object variable of type SqlConnectionand
Initialisesthe variable to a new connection.
25
MyVbDbConnecting to a Database
For MyVbDb you will create a module-levelvariableto hold the connection.
Double-click the form now to access its events, andplace the cursor below the class definitionstatementat the top of themodule.
Enter the following statement:
Private myCn As New
SQLConnection()
26
MyVbDbConnecting to a Database
Before using thisconnection, you must specify the datasourceto whichyouwant to connect.
This isdone through theConnectionStringpropertyofthe ADO.NETconnection object.
The ConnectionString contains connectioninformationsuchas
the name of the provider,
username,and
password.
The ConnectionString might contain manyconnectionparameters
27
MyVbDbSome Parameters for the SQL ConnectionString
28
the set of parameters availab le varies, depending on the source of data to whichyoureconnecting.
If youspecify multipleparameters,separate themwitha semicolon.
In our case, Microsoft SQL.
-
7/25/2019 APII 4b DB
8/23
4/22/20
MyVbDbConnecting to a Database
TheProvider= parameter is one of the mostimportant at this point; it depends on the typeof database youre accessing.
In our example, you access a Microsoft SQLdatabase, so you use the provider information forMicrosoft SQL
In addition to specifying the provider, you alsoneed to specify the database.
We will use the Test.mdfdatabase.
29
MyVbDbConnecting to a Database
Specify the ConnectionString property of yourADO.NET connection by placing the following statementin your formsLoad event:
myCn.ConnectionString = "Data
Source=.\SQLEXPRESS; AttachDbFilename = " & _
"D:\Test.mdf;Integrated Security=True;
Connect Timeout=30;" & _
"User Instance=True "
The code assumes that youve placed the database in
the D: drive. Change it to suit your ownpath.
30
MyVbDbConnecting to a Database
After the connection string is defined, you establisha connection to a data source by using the Open()methodof theconnectionobject.
Add the following statement to theLoad event, rightafter the statement that sets the connectionstring:
myCn.Open()Different types of data sources and different versions of different data sources have diff erent
connection information. The best way t o determine the connection string is to consult the online
documentation for the data source to which you want to attach i.e. if you are not using M icrosoft SQL
Server databasescheck onlinef or information on connectionstrings for other data providers.
31
MyVbDbClosing a Connection to a Data Source
Do not rely on a variable going out of scope to close aconnection to a data source.
Instead, youshould forcean explicit disconnectvia code.
write code to explicitly close theconnectionwhenthe formis closed
Call the Close()method of the connectionobject.
1. Open the object drop-downlist in the code window and selectMainFormEventsif it isnt already selected.
2. ChooseFormClosed from the event dropdown list to createan event handler for the FormClosedevent.
3. Enter thefollowing statementsin theFormClosed event:
myCn.Close()
myCn.Dispose()
32
-
7/25/2019 APII 4b DB
9/23
4/22/20
The DataTableObject
Manipulating Data33
DataTableObjects
A DataTable object containsthe result set of a table,query,or stored procedure.
The easiest way to manipulate data/ records whenusing ADO.NET.
Use a DataTable object to manipulate records:
add,
edit,
delete,
find
navigate
34
DataTables
DataTablescontain a snapshot of the data in thedata source.
To populate a DataTable, you must create anSqlDataAdapter.
We usually
first populate a DataTable, using theDataAdapterobjectsFill() methodthen
manipulate its results, and
f inally send the changesback to the data source (the db inthiscase) using the SqlDataAdaptersUpdate() method.
35
DataTables
Any changes made to the DataTableappear only in the local copy of the datauntil youcall the Update method.
Q:Whyhavealocalcopyof thedata?
Reduces contention by preventing users fromblocking otherswho want to read the data in
thedata source.
36
-
7/25/2019 APII 4b DB
10/23
4/22/20
DataAdapters
To populate a DataTable, you must createan SqlDataAdapter.
The DataAdapter
uses the connection youve already definedto connect to the data sourceand then
executesa query youprovide.
The results of that query are pushed intoa DataTable.
37
DataAdapters
The .NET Framework has many connection
objects including: the Ol eDbConnection object
and the SqlConnection object.
It has multiple ADO.NET DataAdapter objectsaswell.
Youll use the SqlDataAdapterbecause youwillbe connecting to Microsoft SQLServer.
38
Creating DataAdapters
The constructor for an SqlDataAdapter has thefollowingsyntax:
Dim daSqlDataAdapter As NewSqlDataAdapter([CommandText],[Connection])
The constructor hasoptional parametres
the command to executewhen filling a DataTableorDataSet
a connectionspecifying thedata source
youcould have multiple connectionsopen in a single project
39
Creating a DataAdapter
To add an SqlDataAdapter to your MyVbDbproject:
Private myDA As SqlDataAdapter
Create it as a module-level variable:
i.e.intheclassheader
, not in the Load event
Add this statement immediately below thestatement youentered to declare themyCnobject
40
-
7/25/2019 APII 4b DB
11/23
4/22/20
Creating a DataAdapter
Add the following statement at the bottom ofthe forms Load event (immediately followingthestatement that openstheconnection):
myDA = New SqlDataAdapter("Select *
From Contacts", myCn)
41
Creating a DataAdapter
You will use theSqlDataAdapter toupdate theoriginal datasource.
Therefore you must specify the insert,update, anddeletestatements to use to submit changes fromthe DataTable to thedata source.
ADO.NET lets you customise how updates are submitted byenabling you to manually specify these statements asdata base commandsorstored procedures.
Usually (and also for the case of MyVbDb), we let ADO.NETautomatically generate these statements by creating aCommandBuilder object.
42
Creating a DataAdapter
To create the CommandBuilder module level variable, enterthisstatement in theclassheader:
Private myCB As SqlCommandBuilder
Af ter you initialise a CommandBuilder object it handles theupdating,inserting,anddeletingof databehind the scenes.
To make this work, you have to attach the CommandBuilder toanSqlDataAdapter.
passan SqlDataAdapter to the CommandBuilder.
The CommandBuilder then registers forupdateeventson theSqlDataAdapter and provides the insert, update, and deletecommandsasneeded.
43
Creating a DataAdapter
To initialise theCommandBuilderobject add thefollowing statement to the end of the Form_Loadevent
myCB =New SqlCommandBuilder(myDA)
See the next slide for how your code looks like so
far.
44
-
7/25/2019 APII 4b DB
12/23
4/22/20
MyVbDb45
Summary of Steps So Far
Since you jump around a lot in this example follow the stepsexactly:
1. Create amodule-levelvariabletoholdtheconnection(i.e.instantiateaconnectionobject)
PrivatemyCnAsNewSQLConnection()
2. Specifythedatasourceyoureconnectingtheobjectto
by specifying theConnectionString propertyof your ADO.NETconnection(give theparametresof theConnectionString property)
Placethefollowing statement in your formsLoadevent:
myCn.ConnectionString="DataSource=.\SQLEXPRESS;AttachDbFilename=" &_
"D:\Test.mdf;IntegratedSecurity=True;ConnectTimeout=30;"&_
"UserInstance=True"
46
Summary of Steps So Far
3. Establish the connection between the connection objectandthedatasourceby adding the following statement to theLoadevent:
myCn.Open()
4. Explicitly disconnect the connection object fromthe datasourceby calling the Close()method of theconnectionobject. Open the object drop-down list in the code window and selectMainForm
Eventsif it isnt already selected.
Choose FormClosed fromthe event dropdown list to create an event handler fortheFormClosedevent.
Enterthe following statementsin theFormClosed event:
myCn.Close()
myCn.Dispose()
47
Summary of Steps So Far
5. Toenableyoutofill yourDataSetand/orupdateyourdatasource, add an SqlDataAdapter to your project.
Create a module-level object variable of typeSqlAdapter
PrivatemyDAAsSqlDataAdapter
6. Initialise the SqlAdapter object variable to a newSqlDataAdapter and pass to its parametres the commandtext and connection.
Add the following statement to the formsLoadevent:
myDA = New SqlDataAdapter("Select * From Contacts",myCn)
48
-
7/25/2019 APII 4b DB
13/23
-
7/25/2019 APII 4b DB
14/23
4/22/20
MyVbDb
The codeyouhave writtenso far
accessesa database and
creates a DataTable that can be usedanywhere in the class.
Your class should now look like theone shownin the next slide.
53
MyVbDb54
Summary of Steps So Far (cont)
9. Declaring a newmodule-level DataTable objectthat willhold a referenceto data
PrivatemyDataTableAsNewDataTable
10. Use an integer variable to keep track of the users currentposition (row) within theDataTable.
Add the following statement immediately below the statement youjust entered:
PrivatemyRowPositionAsInteger=0
11. To f ill the DataTable with data add the following statement
to the formsLoadevent, after theexisting code:myDA.Fill(myDataTable)
55
Referencing Fields in a DataRow56
-
7/25/2019 APII 4b DB
15/23
4/22/20
Referencing Fields in a DataRow
DataTablescontain a collection ofDataRows.
To access a row within the DataTable, you specify theordinal (index) of that DataRow.
For example, to accessthe first row of your DataTable:
DimmyDataRowAsDataRow=myDataTable.Rows(0)
Data elements in a DataRow are called columns.
For example, the Test.mdf databasesContactstable has 2columns:
ContactName
State
57
Referencing Fields in a DataRow
To reference the value of a column, you can pass thecolumnname to the DataRow like this:
Change the value of the column.
myDataRow(ContactName) =JohnJuma
Or
Get the value of the column.
strContactName=myDataRow (ContactName)
NB: If you misspell a column name, an exception occurs when the statement
executes at runtime;no errors are raised at compile time.
58
Referencing Fields in a DataRow
Create a procedure to display the currentrecordinthedatatable.
1. Position the cursor after the End Substatement of the MainForm_FormClosedevent, and press Enter a few times to createsome blank lines.
2. Enter the procedure onthe next slide:
59
Referencing Fields in a DataRow
Private Sub ShowCurrentRecord()
If myDataTable.Rows.Count = 0 Then
txtContactName.Text = ""
txtState.Text = ""
Exit Sub
End If
txtContactName.Text = _
myDataTable.Rows(myRowPosition)("ContactName").ToString()
txtState.Text = _myDataTable.Rows(myRowPosition)("State").ToString()
End Sub
60
-
7/25/2019 APII 4b DB
16/23
4/22/20
Referencing Fields in a DataRow
3. Ensure that the first record in the DataTable isshownwhenthe formfirst loads
Add this statement to the Form_Load event, after theexistingstatements:
Me.ShowCurrentRecord()
To display the data, you must add a few controls tothe form.
61
Referencing Fields in a DataRow62
Referencing Fields in a DataRow
Press F5 to run the project. The first contact in the Contactstable isdisplayed in the text box:
63
Navigating Records
The ADO.NETDataTable object supportsa number ofmethods that canbe used to accessits DataRows.
The simplest of these is the ordinal accessor that youused in your ShowCurrentRecord()method.
theprocedureyoucreatedtodisplaythecurrentrecordinthedatatable.
The DataTable has no dependency on the source ofthe data.
Therefore, this same functionality is availableregardlessof where the data comesfrom.
64
-
7/25/2019 APII 4b DB
17/23
4/22/20
Navigating Records65
Navigating Records
3. Double-click the button, and add the following codeto itsClick event:
' Move to the first row and show the data.
myRowPosition = 0
Me.ShowCurrentRecord()
66
Navigating Records67
' If not at the first row, go back one row and show the record.
If myrowPosition > 0 ThenmyRowPosition = myRowPosition - 1
Me.ShowCurrentRecord()
End If
btnMovePrevious
Navigating Records68
' If not on the last row, advance one row and show the record.
If myRowPosition < (myDataTable.Rows.Count - 1) ThenmyRowPosition = myRowPosition + 1
Me.ShowCurrentRecord()
End If
btnMoveNext
-
7/25/2019 APII 4b DB
18/23
4/22/20
Navigating Records69
' If there are any rows in the data table, move to the last
' and show the record.IfmyDataTable.Rows.Count > 0 Then
myRowPosition = myDataTable.Rows.Count - 1
Me.ShowCurrentRecord()End If
Editing Records
To edit records in a DataTable, you change thevalue of a particular column in the desiredDataRow.
Remember
Changes arent made to the original datasource until you call Update() on theSqlDataAdapter, passing in the DataTablecontaining thechanges.
70
Editing Records
To add a button that the user can click to updatethecurrent record:
71
Editing Records
2. Double-click the Save button, and add thefollowing code to itsClick event:
' If there is existing data, update it.
If myDataTable.Rows.Count 0 Then
myDataTable.Rows(myRowPosition)("ContactName
") = txtContactName.Text
myDataTable.Rows(myRowPosition)("State") =
txtState.Text
myDA.Update(myDataTable)
End If
72
Youve updated the DataTable then passed it to the DataAdapters Update Method.
-
7/25/2019 APII 4b DB
19/23
4/22/20
Creating New Records
Adding records to a DataTable is similar to editingthem.
However, to create a new row in the DataTable, youmust first call the NewRow()method.
After creating the new row, you can set its columnvalues.
The row isnt actually added to theDataTable, however, until you call the Add()methodon the DataTablesRowCollection.
73
Creating New Records
Modify your interface so that the user can addnewrecords.
Have two textboxesthat will be used for:
the contact name and
thestate.
When the user clicks the button you provide,the valuesin these text boxesare writtento theContactstable asa new record.
74
Creating New Records75
Creating New Records76
-
7/25/2019 APII 4b DB
20/23
4/22/20
Creating New Records
5. Double-click the Add button, and add thefollowing code to itsClick event:
Dim drNewRow As DataRow = myDataTable.NewRow()
drNewRow("ContactName") = txtNewContactName.Text
drNewRow("State") = txtNewState.Text
myDataTable.Rows.Add(drNewRow)
myDA.Update(myDataTable)
myRowPosition = myDataTable.Rows.Count 1
Me.ShowCurrentRecord()
77
Creating New Records
Notice that after the new record is added, theposition is set to the last row, and theShowCurrentRecord() procedure is called.
This causes the new record to appear in the displaytext boxesyoucreated earlier.
78
Deleting Records
To delete a record from a DataTable, you call theDelete()methodonthe DataRowto be deleted.
79
Deleting Records
2. Double-click the Delete button, and add thefollowing code to itsClick event:
' If there is data, delete the current row.
If myDataTable.Rows.Count 0 Then
myDataTable.Rows(myRowPosition).Delete()
myDA.Update(myDataTable)
myRowPosition = 0
Me.ShowCurrentRecord()
End If
80
-
7/25/2019 APII 4b DB
21/23
4/22/20
MyVbDb81
Your form should now look like this: Running MyVbDb82
Running MyVbDb
PressF5 to runthe project.
If you entered all the code correctly and you placed theContacts database in the D: drive (or modified the path usedin code), the form should be displayed without errors, and thefirst record in the database appears.
Click thenavigationbuttonsto move forward and backward.
Changea contactsinformation; click the Save button
your changesare made to theunderlying database.
Next, enter anewname and state into the New Contact
sectionof the form, and clickAdd. The name is added to the database and displayed in the
appropriate text boxes.
83
MyVbDbThe Entire Code
Public ClassMainForm
Private myCnAsNew SqlConnection()
Private myDA AsSqlDataAdapter
Private myCBAsSqlCommandBuilder
Private myDataTable AsNew DataTable
Private myRowPositionAsInteger = 0
84
-
7/25/2019 APII 4b DB
22/23
4/22/20
MyVbDbThe Entire CodePrivate Sub MainForm_FormClosed(sender As Object, e As
FormClosedEventArgs) Handles Me.FormClosed
myCn.Close()
myCn.Dispose()
End Sub
Private Sub ShowCurrentRecord()
If myDataTable.Rows.Count = 0 Then
txtContactName.Text = ""
txtState.Text = ""
Exit Sub
End If
txtContactName.Text = _
myDataTable.Rows(myRowPosition)("ContactName").ToString()
txtState.Text = _
myDataTable.Rows(myRowPosition)("State").ToString()
End Sub
85
MyVbDbThe Entire CodePrivate Sub MainForm_Load(sender As Object, e As
EventArgs) Handles MyBase.Load
myCn.ConnectionString ="Data Source=.\SQLEXPRESS;
AttachDbFilename = " & _
"D:\Test.mdf;Integrated Security=True; Connect
Timeout=30;" & _
"User Instance=True
myCn.Open()
myDA = New SqlDataAdapter("Select * From
Contacts", myCn)
myCB =New SqlCommandBuilder(myDA)
myDA.Fill(myDataTable)
Me.ShowCurrentRecord()
End Sub
86
MyVbDbThe Entire CodePrivate Sub btnMoveFirst_Click(sender As Object, e AsEventArgs) Handles btnMoveFirst.Click
' Move to the first row and show the data.
myRowPosition = 0
Me.ShowCurrentRecord()
End Sub
Private Sub btnMovePrevious_Click(sender As Object, e AsEventArgs) Handles btnMovePrevious.Click
' If not at the first row, go back one row and show therecord.
If myrowPosition > 0 Then
myRowPosition = myRowPosition - 1
Me.ShowCurrentRecord()
End If
End Sub
87
MyVbDbThe Entire Code
Private SubbtnMoveNext_Click(sender As Object, e As EventArgs)HandlesbtnMoveNext.Click
' If not on the last row, advance one row and show the record.
If myRowPosition < (myDataTable.Rows.Count - 1) Then
myRowPosition = myRowPosition + 1
Me.ShowCurrentRecord()
End If
End Sub
Private Sub btnMoveLast_Click(sender As Object, e As EventArgs)
Handles btnMoveLast.Click
' If there are any rows in the data table, move to the last and
' show the record.
If myDataTable.Rows.Count > 0 Then
myRowPosition = myDataTable.Rows.Count - 1
Me.ShowCurrentRecord()
End If
End Sub
88
-
7/25/2019 APII 4b DB
23/23
4/22/20
MyVbDbThe Entire CodePrivate Sub btnSave_Click(sender As Object, e As
EventArgs) Handles btnSave.Click
' If there is existing data, update it.
If myDataTable.Rows.Count 0 Then
myDataTable.Rows(myRowPosition)("ContactName")
= txtContactName.Text
myDataTable.Rows(myRowPosition)("State") =
txtState.Text
myDA.Update(myDataTable)
End If
End Sub
89
MyVbDbThe Entire CodePrivate Sub btnAddNew_Click(sender As Object, e As
EventArgs) Handles btnAddNew.Click
Dim drNewRow As DataRow = myDataTable.NewRow()
drNewRow("ContactName") = txtNewContactName.Text
drNewRow("State") = txtNewState.Text
myDataTable.Rows.Add(drNewRow)
myDA.Update(myDataTable)
myRowPosition = myDataTable.Rows.Count 1
Me.ShowCurrentRecord()
End Sub
90
MyVbDbThe Entire CodePrivate Sub btnDelete_Click(sender As Object, e As
EventArgs) Handles btnDelete.Click
' If there is data, delete the current row.
If myDataTable.Rows.Count 0 Then
myDataTable.Rows(myRowPosition).Delete()
myDA.Update(myDataTable)
myRowPosition = 0
Me.ShowCurrentRecord()
End If
End Sub
End Class
91
Key Terms
auto-generated field BindingSource object components compound primary key database databaseschema data binding data-bound control DataGridView control DataSet DataTable data source DataSource property DisplayMember property
foreign key
identity fieldLIKE operatorone-to-many relationship
ORDER BY clauseprimary key
query parameterrelational database modelSELECT statement
Structured Query Language (SQL)TableAdapter
WHERE clausewildcard symbolxcopy deployment
92