Visual Basic Database Access

Download Report

Transcript Visual Basic Database Access

Introduction to ADO.Net, VB.Net
Database Tools and Data Binding
ISYS546
Steps to Retrieve Data
• Establishes a connection to the database.
• Executes commands against the database.
• Store data results.
A Simplified View of ADO.Net
Objects
Ado.Net
Data Provider
Data Consumer
Adapter
Dataset
WinForm
Connection
Command
WebForm
Reader
ADO.NET Objects
• Connection Object: Represent a connection to the
database.
• Command Object: The command object allows us
to execute a SQL statement or a stored procedure.
• DataReader: It is a read-only and forward-only
pointer into a table to retrieve records.
• DataSet Object: A DataSet object can hold several
tables and relationships between tables.
• DataAdapter: This the object used to pass data
between the database and the dataset.
Data Providers
• ODBC Provider
– Open Database Connectivity
• A driver manager
• Used for relational databases
• OLE DB Provider
– OLE DB interfaces provide applications with uniform
access to data stored in diverse information sources, or
data stores.
– Access
• SQL Server Provider
• Oracle Provider
Using ODBC
• Windows XP:
• Control Panel /Administrative Tools/DataSource(ODBC)
• Three types of data source names
– User DSN: usable only by you and only on the machine
currently using.
– System DSN: Any one using the machine can use.
– File DSN: Can be copied and used by other computers
with the same driver installed.
VB.NET Database Tools
• Database connection:
– Tools/Connect to database
• Data Source
• Server Explorer
– Data connections: Right click data connection
• Add Connection
– Tables, Views
• Create new SQL Server Database
• Toolbox:Data tab
• Data/Add New Data Source
Creating SQL Server Database
• From Server Explorer, right click data connection
and choose:
• Create new SQL Server Database
• Server name:
– LocalServerName\SQLExpress
• Add new table: Right click Tables and choose Add
New Table
• Add rows: Right click the table name and choose
Show table data.
How to create an ADO.Net object?
• Automatically generated when creating
data bound form.
– Form wizard
• Using Data Adapter Wizard
• Using code:
– Example:
– dim strConn as string ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source
= c:\sales2k.mdb"
– dim objConn as new OledbConnection(strConn)
– objConn.open()
Data Binding
• Connect a control or property to one or more data
elements.
• Simple binding: Use simple binding to display a
field value in controls that show Data Bindings in
the property window, such as text box or label.
• Complex binding: Use complex binding to bind
more than one field to controls such as DataGrid
and list box. Use the control’s Data Source and
Data Member to bind the data.
Creating Data Bound Form
• Creating a form with ADO.Net objects and databound controls to display and update information
in a dataset.
• Demo:
– Add data source.
– Click the dropdown list next to the table’s name:
• Datagrid view
• Details
– Drag the table to form.
Items Added to the Form
• Connection
• Table Adapter: click smart tag
– Add query
– Preview data
• Dataset:
– Edit in dataset designer
• Binding Source
– Add query: Add a new tool strip.
– Preview data
• Binding navigator
• Code view: Form load event
– Me.CUSTOMERTableAdapter.Fill(Me.Sales2KDataSet.C
USTOMER)
Other Data Form Demos
• DataGrid View
• Add /Modify/Delete records.
• Read only form:
– Delete AddNew, Delete, Save buttons from navigator bar.
• Hierarchical forms:
– Dataset has Tables collection and Relations collection.
• Parent/Child relation
– Drag the parent table and the child table to the form.
Parent table uses detail view and child table uses
dataGrid view
– Change dataGrid’s DataSource property to the relation.
Creating A Database Application
Without Programming
• Creating a database application to display
information and update database.
• A main form with buttons to open data
forms:
–
–
–
–
DisplayInfo
Enter New
Modify
Exit
Data Adapter Wizard
• Configure Data Adapter and generating a dataset:
– From the Data tab of the ToolBox, Drag
OledbDataAdapter to the form.
– Use the Data Adapter Wizard to configure the Adapter.
– Right Click the Adapter to preview data and create
dataset.
• Bind the dataset to controls.
• In the Form Load event, use Adapter’s Fill method
to load the dataset:
• OleDbDataAdapter1.Fill(DataSet11)
Creating Bound DataGridView
• DataGridView control:
– Data Source property:
• DataSet
– Data Member property
• A table in the dataset
– In the Form Load event, use Adapter’s Fill
method to load the dataset:
• OleDbDataAdapter1.Fill(DataSet11)
Objects Related to Data Binding
• BindingContext: It is an object that manages a
collection of data sources used for binding.
• CurrencyManager: It is an object that keeps track
of position (the current row) of a data source. Two
useful properties:
– Position property: is the index of the current row. The
index is a 0-based index, the first record has a position
of 0.
– Count property: The number of rows in the data source.
Binding Text Box
• Select Data Bindings property:
– Text: choose field
• Add navigation buttons:
– The current record position within the data
source is stored in the CurrencyManager’s
Position property. This position is zero based.
Add one move to the next record, minus one
move to the previous record.
MoveNext and MoveLast Example
• MoveNext:
–
Me.BindingContext(DataSet21, "customer").Position += 1
• MoveLast:
– Me.BindingContext(DataSet21, "customer").Position =
Me.BindingContext(DataSet21, "customer").Count -1
• How to MovePrevious and MoveFirst?
• Note: The Position property takes care of the end of file
automatically.
• Note: Me.BindingContext(DataSet21, "customer") returns
a CurrencyManager object.
BindingSource Object
• BindingSource is an object that
encapsulates a CurrencyManager and its
properties and methods.
• It has two important properties: DataSource
and DataMember.
• In case that the data source for a control
changes, we only need to change the
DataSource and DataMember properties.
BindingSource’s Position Property
• If controls are bound to a BindingSource
object, to move the current record we
change the Position property of the
BindingSource object:
– To move to the next record:
• Me.EmpBindingSource.Position += 1
– To move to the previous record:
• Me.EmpBindingSource.Position -= 1
CurrencyManager
• Dim custCurrMgr As CurrencyManager
• Dim ordCurrMgr As CurrencyManager
• In a procedure:
–
–
–
–
ordCurrMgr = Me.BindingContext(Ds31, "orders")
custCurrMgr = Me.BindingContext(Ds31, “customer")
custCurrMgr.Position += 1
ordCurrMgr.Position += 1
BindingNavigator Object
• This object automatically adds navigation
buttons to the form.
• Property:
– BindingSource property
Binding ListBox
• Example: Bind Customer Table’s CID field to a
listbox.
– Create a Adapter for Customer table , and generate the
dataset.
– Add ListBox and set binding properties:
• Data Source: Customer table
• Display Member: Field to display in the listbox.
• Value Member: the actual values for items in the list box. To
display the selected item’s value in a text box, do:
– Textbox1.text = ListBox1.SelectedValue
• Can we use TextBox1.text=ListBox1.SelectedItem?
No!
Display Selected Record
• Bound textbox (same data source as the
listbox):
– If the Listbox and the textbox are bound to the
same BindingSource object, the textbox will
automatically displays the record of the selected
listbox item.
• Unbound textbox
ListBox SelectedItem Property
• How to display the selected record in unbound
textbox?
• After binding to a data source, this property return a
DataRowView object.
• What is DataRowView?
– Object Browser:
• System.Data
– DataRowView:
Item property is the default property
• To retrieve a column from a DataRowView object
(use 0-based index to identity a column):
• ListBox1.SelectedItem.Item(1)
• Or: ListBox1.SelectedItem(1)
• Or: ListBox1.SelectedItem(“Cname”)
An Easy Away to Create a Form with
Listbox and Textboxes
• Example: Display CID in Listbox and Display other fields
of a customer record in textboxes
• 1. Click the DataSource window
• 2. Select the Customer table
• 3. Select CID field and click the drop down list next to it to
change the CID field’s control to listbox.
• 4. Drag the CID field to the form
– Change the DataSource property to CustomerBindingSource and
Display member property to CID
• 5 Drag other fields to the form.
Using Object Browser
• View/Object Browser
• DataSet object model:
• System.Data
– DataSet
• Relations
• Tables
– Rows
– Columns
• Use Object Browser to study object’s properties,
methods.
Collection Structure
• Properties:
– Count
– Item(index), 0-based index
• Methods:
– Clear, Add, Insert, Remove, etc.
DataSet Class Hierarchy
• DataSet
– Tables: A collection of datatable objects
– To retrieve a table from Tables:
• DataSet11.Tables.Item(“CUSTOMER”).
• DataSet11.Tables(“CUSTOMER”).
• DataSet11.CUSTOMER
– Rows: Each table has a Rows property which is a
collection of dataRow objects
• To get the first row:
DataSet11.Tables(“CUSTOMER”).Rows(0)
– Each DataRow object has a collection of fields. To
retrieve a field:
• DataSet11.CUSTOMER.Rows(0).Item(1)
• How many tables in a dataset?
• How many records in a table?
Navigate and Display Records in
Unbound Text Boxes
• Use code to assign field value to the text
box’s text property.
• Example:
– Dim drFound As DataRow
– drFound = DataSet11.CUSTOMER.Rows(0)
• Or DataSet11.Tables(“CUSTOMER”).Rows(0)
– TextBox4.Text = drFound.Item("cname")
• Or drFound.Item(1)
– Or: TextBox4.Text =
DataSet11.CUSTOMER.Rows(0).Item(1)
– Or: DataSet21.Tables.Item("customer").Rows.Item(0).Item(1)
Implement MoveNext Button
with Unbound Control
If rowIndex < DataSet11.CUSTOMER.Rows.Count-1 Then
rowIndex += 1
TextBox1.Text = DataSet11.Tables("customer").Rows(rowIndex).Item(0)
TextBox2.Text = DataSet11.CUSTOMER.Rows(rowIndex).Item(1)
Else
MsgBox("out of bound")
End If
Note: MovePrevious, MoveLast, MoveFirst?
Using Object Browser to Study OleDB
Object
• System.Data
– System.Data.OleDB
• OleDBConnection
– Methods: New(), New(ConnectionString), Open(), Close()
– Properties: ConnectionString, DataBase, Provider, TimeOut
• OleDBCommannd
– Methods: ExecuteReader, ExecuteNonQuery
– Properties: Connection, CommandType, CommandText,
Parameters
• OleDBDataAdapter
– Methods: Fill
– Properties: SelectCommand, InsertCommand, DeleteCommand,
UpdateCommand.
Use the Find method of Table’s
Rows collection to find a record
• Gets the row that contains the specified
primary key values.
– DataSet41.CUSTOMER.Rows.Find(ListBox1.
SelectedValue)
– The FIND method returns a DataRow object.
• Display the found record in unbound text
boxes.
Code Example
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
ListBox1.SelectedIndexChanged
Dim drFound As DataRow
drFound = DataSet41.CUSTOMER.Rows.Find(ListBox1.SelectedValue)
‘ Assume SelectedValue is CID
TextBox1.Text = drFound.Item("cname")
TextBox2.Text = drFound.Item("rating")
End Sub
Note: We can get the search value from other controls such as InputBox
and Textbox.
How to Determine If Record Exists
or Not
Dim foundRow As DataRow
Dim SearchValue as String
SearchValue=InputBox(“Enter CID”)
foundRow = DataSet41.CUSTOMER.Rows.Find (SearchValue)
If Not (foundRow Is Nothing) Then
TextBox1.Text = FoundRow.Item("cname")
TextBox2.Text = FoundRow.Item("rating")
Else
Messagebox.show(“Record not exist”)
End If
Send Changes in a Bound DataGrid
Back to the Database
• Updating records in DataGrid:
– New records are added at the end of the grid.
– To delete a record, click the leftmost column to select
the record, then press the delete key.
– Modify record
• Add an Update button that use adapter’s update
method to send changes back to the data source:
– OledbDataAdapter1.Update(Dataset11)
How to create a dataset with two
tables and relation?
• Assuming we want to create a database with
Customer and Orders tables:
• You need to create two adapters, one for the
Customer table and one for the Orders table. Then
generate dataset from the adapters.
• The dataset created from the two adapters will
contain both tables.
• To create a relation between the two tables, double
click the dataset to open the dataset’s design view.
At the dataset’s design view, point to the Customer
table and right click to Add relation.