ADO.NET in VB.NET 2005

44
06/10/22 1 ADO.NET in VB.NET ADO.NET in VB.NET 2005 2005 ITE 370 ITE 370

description

ADO.NET in VB.NET 2005. ITE 370. What is ADO.NET?. An acronym for the .NET version of ActiveX Data Objects A .NET Framework Class Library A group of types that reside in System.Data namespace A technology used by client applications to work with stored data Supported data formats include: - PowerPoint PPT Presentation

Transcript of ADO.NET in VB.NET 2005

Page 1: ADO.NET in VB.NET 2005

04/20/23 1

ADO.NET in VB.NET ADO.NET in VB.NET 20052005

ITE 370ITE 370

Page 2: ADO.NET in VB.NET 2005

04/20/23 2

What is ADO.NET?What is ADO.NET? An acronym for the .NET version of ActiveX An acronym for the .NET version of ActiveX

Data ObjectsData Objects A .NET Framework Class LibraryA .NET Framework Class Library A group of types that reside in System.Data A group of types that reside in System.Data

namespacenamespace A technology used by client applications to A technology used by client applications to

work with stored datawork with stored data Supported data formats include:Supported data formats include:

relational databases (MS-Access, SQL-Server, and relational databases (MS-Access, SQL-Server, and Oracle)Oracle)

Spreadsheets and other file formatsSpreadsheets and other file formats XMLXML

Page 3: ADO.NET in VB.NET 2005

04/20/23 3

Providers and Their Providers and Their NamespacesNamespaces What is a “provider”?What is a “provider”?

.NET data provider.NET data provider Software for accessing a specific source of Software for accessing a specific source of

data, such as SQL-Serverdata, such as SQL-Server Optimized classes for SQL-ServerOptimized classes for SQL-Server

Namespace: System.Data.SqlClientNamespace: System.Data.SqlClient OLE DB clientOLE DB client

For MS-Access, Excel, and othersFor MS-Access, Excel, and others Also has support for Oracle and SQL-ServerAlso has support for Oracle and SQL-Server Namespace: System.Data.OledbNamespace: System.Data.Oledb

Page 4: ADO.NET in VB.NET 2005

04/20/23 4

otherDBMS

client

SQL.NET DataProvider

OLE DB.NET DataProvider

other.NET dataproviders

MSAccess

SQLServer

How clients, .NET data How clients, .NET data providers &DBMSs fit providers &DBMSs fit togethertogether

Page 5: ADO.NET in VB.NET 2005

04/20/23 5

Types of ADO.NET Types of ADO.NET objectsobjects Connection – establishes links to data sourcesConnection – establishes links to data sources Command – stores and executes commands (i.e. queries and Command – stores and executes commands (i.e. queries and

stored procedures with parameters)stored procedures with parameters) DataReader – provides sequential, read-only access to dataDataReader – provides sequential, read-only access to data TableAdapter – pulls data from one or more database tables TableAdapter – pulls data from one or more database tables

and passes it to your programand passes it to your program DataSet – an in-memory copy of data pulled from the DataSet – an in-memory copy of data pulled from the

database tables (by the Table Adapter) database tables (by the Table Adapter) DataTable – stores a relation—eg. the result of a queryDataTable – stores a relation—eg. the result of a query DataRelation – defines a relationship between two DataRelation – defines a relationship between two

DataTablesDataTables DataRow – stores a single row/record of a data tableDataRow – stores a single row/record of a data table DataColumn – represents schema in a column of a DataColumn – represents schema in a column of a

DataTableDataTable DataView -- customized view of a DataTable for sorting, DataView -- customized view of a DataTable for sorting,

filtering, searching, editing, and navigation. filtering, searching, editing, and navigation. DataGrid – tabular control for displaying/editing a data DataGrid – tabular control for displaying/editing a data

sourcesource

Page 6: ADO.NET in VB.NET 2005

04/20/23 6

Working with .udl files to Working with .udl files to build connection stringsbuild connection strings

To create a UDL file:To create a UDL file:1.      Open Windows Explorer or My Computer. 1.      Open Windows Explorer or My Computer. 2.      Select the folder in which you want to save the .UDL file. 2.      Select the folder in which you want to save the .UDL file. 3.      On the File menu, click NEW and then click Text Document. 3.      On the File menu, click NEW and then click Text Document. 4.      Right-click on the text file you created in step 3, then click 4.      Right-click on the text file you created in step 3, then click

Rename. Type the new file name using a .udl file extension. Press Rename. Type the new file name using a .udl file extension. Press Enter. For example. Myudl.UDLEnter. For example. Myudl.UDL

5.      You may get a warning, message box, explaining that changing 5.      You may get a warning, message box, explaining that changing file extensions may cause files to become unusable. This is fine, file extensions may cause files to become unusable. This is fine, click OK.click OK.

  Once you have created the UDL file, you must now configure it:Once you have created the UDL file, you must now configure it:1.1. Double click on the UDL file to bring up the Data Link Properties Double click on the UDL file to bring up the Data Link Properties

Dialog Box. Dialog Box. 2.2. Click on the Providers tab and select the driver you wish to use. Click on the Providers tab and select the driver you wish to use. 3.3. Click on the Connection tab and enter the connection properties, Click on the Connection tab and enter the connection properties,

each driver will require different settings, so I will not go into much each driver will require different settings, so I will not go into much details. All drivers will require a user name and password. details. All drivers will require a user name and password.

4.4. Click on the “Test Connection” button to verify your connection is Click on the “Test Connection” button to verify your connection is working correctly. Change accordingly if you get an error. working correctly. Change accordingly if you get an error.

5.5. Select the advanced tab only if you require advanced settings. Select the advanced tab only if you require advanced settings.

Source: K & K Consulting, http://kandkconsulting.tripod.com/VB/Tutorials/udl_file_tutorial.htm

Page 7: ADO.NET in VB.NET 2005

04/20/23 7

Create Data Source String Create Data Source String for Connection Objectfor Connection Object

Example of how to create the Data Source Example of how to create the Data Source StringString

Page 8: ADO.NET in VB.NET 2005

04/20/23 8

DataReader ClassDataReader Class

The DataReaderThe DataReader Provides Provides forward-only, read-onlyforward-only, read-only access to access to

datadata Analogous to reading a sequential fileAnalogous to reading a sequential file Read from beginning of file in order to the end Read from beginning of file in order to the end

of fileof file Fast access to dataFast access to data Uses little memoryUses little memory Requires connection and command objects to Requires connection and command objects to

useuse

Page 9: ADO.NET in VB.NET 2005

04/20/23 9

DataReader ExampleDataReader ExampleImports System.Data.OledbImports System.Data.Oledb

Public Class ConnDbPublic Class ConnDb '* Declare constant to hold base connection string information'* Declare constant to hold base connection string information '* for connecting to an MS-Access baseball database (connection string from UDL file).'* for connecting to an MS-Access baseball database (connection string from UDL file). Public Const ConnStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;" _Public Const ConnStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;" _ & "Persist Security Info=False;Data Source=“ ‘* & "Persist Security Info=False;Data Source=“ ‘* notice we removed name of filenotice we removed name of fileEnd ClassEnd Class

'* Declare data access objects'* Declare data access objectsDim conTeamDb As OleDbConnection '* connects to baseball databaseDim conTeamDb As OleDbConnection '* connects to baseball databaseDim dbCommand As OleDbCommand '* executes database query for team Dim dbCommand As OleDbCommand '* executes database query for team Public rdrTeams As OleDbDataReader '* forward-only, read-only access to team relationPublic rdrTeams As OleDbDataReader '* forward-only, read-only access to team relationDim OpenDbDialog As New OpenFileDialogDim OpenDbDialog As New OpenFileDialog

‘‘* If the user selects a database in the open dialog box...* If the user selects a database in the open dialog box...If OpenDbDialog.ShowDialog() = DialogResult.OK ThenIf OpenDbDialog.ShowDialog() = DialogResult.OK Then '* connect to the database'* connect to the database conTeamDb = New OleDbConnection(ConnDb.ConnStr & OpenDbDialog.FileName)conTeamDb = New OleDbConnection(ConnDb.ConnStr & OpenDbDialog.FileName) conTeamDb.Open()conTeamDb.Open()

'* query the team table, assigning result to a data reader'* query the team table, assigning result to a data reader dbCommand = New OleDbCommand("SELECT Location, Nickname, Stadium, League FROM Team", conTeamDb)dbCommand = New OleDbCommand("SELECT Location, Nickname, Stadium, League FROM Team", conTeamDb) rdrTeams = dbCommand.ExecuteReaderrdrTeams = dbCommand.ExecuteReader

If rdrTeams.Read() '* success reading next teamIf rdrTeams.Read() '* success reading next team Console.WriteLine(rdrTeams.Item("Location") & " " & rdrTeams("Nickname"))Console.WriteLine(rdrTeams.Item("Location") & " " & rdrTeams("Nickname")) End ifEnd if rdrTeams.Close()rdrTeams.Close() conTeamDb.Close()conTeamDb.Close()End IfEnd If

Page 10: ADO.NET in VB.NET 2005

04/20/23 10

View Sample Project Using View Sample Project Using Data ReaderData Reader Create New VB.Net ApplicationCreate New VB.Net Application Add ListTeams.VBAdd ListTeams.VB Project Properties Project Properties StartUP StartUP

Sub Main ( )Sub Main ( ) Run Sample Application Using Data Run Sample Application Using Data

ReaderReader Attempt to Add a Form and Have the Data Attempt to Add a Form and Have the Data

Display within the Form instead of to the Display within the Form instead of to the ConsoleConsole

Page 11: ADO.NET in VB.NET 2005

04/20/23 11

Using Table Adapters / Using Table Adapters / Data SetData Set Table Adapter – Retrieves data from the data Table Adapter – Retrieves data from the data

source and updates the data in the data sourcesource and updates the data in the data source Data Connection – Connecting to the Data SourceData Connection – Connecting to the Data Source

Built into the Table Adapter ObjectBuilt into the Table Adapter Object

Data Set – In memory copy of records / data tablesData Set – In memory copy of records / data tables Separate from the data sourceSeparate from the data source Data tables have columns and rowsData tables have columns and rows Allows you to work with the data from the data sourceAllows you to work with the data from the data source Changes are not permanent in external data source Changes are not permanent in external data source

unless directed by the Table Adapterunless directed by the Table Adapter Data is transferred from the data source to the Data is transferred from the data source to the

data set and vice-versa through the Table Adapterdata set and vice-versa through the Table Adapter

Page 12: ADO.NET in VB.NET 2005

04/20/23 12

DataSet w/Multiple DataSet w/Multiple Tables & ProvidersTables & Providers

DataSetSqlTableAdapter

SelectCommand

SQLServer

OracleOleDbTableAdapter

SelectCommand

TableX

TableY

1) Fill(DataSet, “TableX”)

2) Execute query

3) Return DataTable

4) Fill(DataSet, “TableY”)

6) Return DataTable

5) Execute query

Page 13: ADO.NET in VB.NET 2005

04/20/23 13

TableAdapter ClassTableAdapter Class

Provides communication between the Provides communication between the application and databaseapplication and database

Represents a set of data commands and a Represents a set of data commands and a database connection that are used to fill the database connection that are used to fill the DataSet and update the data source based DataSet and update the data source based on querieson queries Can contain multiple queries – called like methodsCan contain multiple queries – called like methods

Created withCreated with CodeCode Dataset Designer Dataset Designer During Creation of a New Dataset – Data Source During Creation of a New Dataset – Data Source

Configuration WizardConfiguration Wizard Server Explorer / Dataset DesignerServer Explorer / Dataset Designer

Page 14: ADO.NET in VB.NET 2005

TableAdapter ClassTableAdapter Class __Command properties (Created through __Command properties (Created through

Queries):Queries): Select Query – Used in Fill MethodSelect Query – Used in Fill Method Insert Command, Update Command, Delete CommandInsert Command, Update Command, Delete Command

Can be Created by default if enough information is available Can be Created by default if enough information is available in the Select query (Fill Method)in the Select query (Fill Method)

Methods:Methods: Fill – populated the Data Table with the result of the select Fill – populated the Data Table with the result of the select

commandcommand Update – Sends changes back to the databaseUpdate – Sends changes back to the database Insert – creates a new row in the data tableInsert – creates a new row in the data table ClearBeforeFill – Clears the data table before executing a fill ClearBeforeFill – Clears the data table before executing a fill

methodmethod

04/20/23 14

Page 15: ADO.NET in VB.NET 2005

04/20/23 15

TableAdapter: TableAdapter: __Command Properties__Command Properties Contain command objects to perform Contain command objects to perform

operations against the underlying operations against the underlying databasedatabase Select CommandSelect Command

Populates a DataTable with the results of a queryPopulates a DataTable with the results of a query Uses SQL SELECT statement typicallyUses SQL SELECT statement typically

Insert CommandInsert Command Inserts rows added to a DataTable into databaseInserts rows added to a DataTable into database Uses SQL INSERT statementUses SQL INSERT statement

Page 16: ADO.NET in VB.NET 2005

04/20/23 16

TableAdapter: TableAdapter: __Command Properties __Command Properties (cont.)(cont.)

UpdateUpdate Writes changes made to a DataTable into the Writes changes made to a DataTable into the

underlying databaseunderlying database Uses SQL UPDATE statementUses SQL UPDATE statement

Delete CommandDelete Command Makes deletions of rows in a DataTable permanent Makes deletions of rows in a DataTable permanent

by deleting those rows from the databaseby deleting those rows from the database Uses SQL DELETE statementUses SQL DELETE statement

Page 17: ADO.NET in VB.NET 2005

04/20/23 17

DataAdapter: Fill MethodDataAdapter: Fill Method

Adds or refreshes rows in the DataSet to Adds or refreshes rows in the DataSet to match those in the data source using the match those in the data source using the DataSet nameDataSet name

Creates a DataTable named "Table"Creates a DataTable named "Table"taEmployee.Fill(dsCompany.AllEmployees)

Table Adapter

Method Data Set Name for Data Table

Page 18: ADO.NET in VB.NET 2005

04/20/23 18

TableAdapter: Update TableAdapter: Update MethodMethod Used to persist changes to a DataTable Used to persist changes to a DataTable

(i.e. save them in the database)(i.e. save them in the database) Calls the respective INSERT, UPDATE, or Calls the respective INSERT, UPDATE, or

DELETE statements for each inserted, DELETE statements for each inserted, updated, or deleted row in the specified updated, or deleted row in the specified DataSet from a DataTable named "Table"DataSet from a DataTable named "Table"

taEmployee.UpdateCommand(dsEmployee)

Page 19: ADO.NET in VB.NET 2005

04/20/23 19

Table Adapter – Through Table Adapter – Through IDEIDE Server ExplorerServer Explorer

Click on Connect to DB IconClick on Connect to DB Icon Add ConnectionAdd Connection

Provide Data Source Type (Access, SQL Server)Provide Data Source Type (Access, SQL Server) Provide Database File Provide Database File Test the ConnectionTest the Connection

Add DataSetAdd DataSet Data Menu Data Menu Add New Data Source Add New Data Source Project Project Add New Item Add New Item DataSet DataSet

Select Items from Open Connection in Server Select Items from Open Connection in Server ExplorerExplorer

Creates the Data Set and Table AdapterCreates the Data Set and Table Adapter

Page 20: ADO.NET in VB.NET 2005

04/20/23 20

Binding SourceBinding Source

Data Aware ControlsData Aware Controls Controls that can automatically display Controls that can automatically display

data from a table cell in the DataSet (most data from a table cell in the DataSet (most VB.net controls are data aware)VB.net controls are data aware)

Controls must be Bound to the DataSetControls must be Bound to the DataSet DataBindings Property of ControlDataBindings Property of Control Arrow next to Text Field (of DataBindings)Arrow next to Text Field (of DataBindings) Add or Select Data SourceAdd or Select Data Source Complete Data Source Configuration WizardComplete Data Source Configuration Wizard

Page 21: ADO.NET in VB.NET 2005

04/20/23 21

Currency ManagerCurrency Manager

Object that gives a way of navigating the Object that gives a way of navigating the rows of the DataTable. One row of the rows of the DataTable. One row of the DataTable is always the current rowDataTable is always the current row Data Aware controls display the data from the Data Aware controls display the data from the

current rowcurrent row Currency Manager objects are included in Currency Manager objects are included in

BindingSource componentsBindingSource components Position Property Position Property Number of the Current Number of the Current

Row (zero based)Row (zero based) Count Property Count Property How many rows are in the How many rows are in the

tabletable

Page 22: ADO.NET in VB.NET 2005

04/20/23 22

Sample Code Sample Code

Create a Visual Basic 2005 Application Create a Visual Basic 2005 Application that will access the Baseball3 database that will access the Baseball3 database and display the player information in and display the player information in bound textboxes. The program should use bound textboxes. The program should use a Table Adapter, Data Set , Binding a Table Adapter, Data Set , Binding Source and Currency Manager to Source and Currency Manager to manipulate through the table data.manipulate through the table data.

Page 23: ADO.NET in VB.NET 2005

Visual Studio.Net Visual Studio.Net WisdomWisdom

Update CommandUpdate Command

TableAdapter.Update (Dataset.DataTable)TableAdapter.Update (Dataset.DataTable)taEmployee.Fill(dsCompany.AllEmployees)taEmployee.Fill(dsCompany.AllEmployees)

Updates the databaseUpdates the database Updates the “local” copy in the Bin directoryUpdates the “local” copy in the Bin directory Copied over by Visual Studio the next time the Copied over by Visual Studio the next time the

program is runprogram is run Don’t want you to corrupt your databasesDon’t want you to corrupt your databases How to accomplish a True Update?????How to accomplish a True Update?????

04/20/23 23

Page 24: ADO.NET in VB.NET 2005

Update Command Update Command

Cannot use the IDE to develop your applicationCannot use the IDE to develop your application Must create the code by hand (Within Class Must create the code by hand (Within Class

Code)Code) Connection ObjectConnection Object DataAdapter ObjectDataAdapter Object DataSet ObjectDataSet Object DataTable ObjectDataTable Object BindingSource ObjectBindingSource Object CommandBuilder ObjectCommandBuilder Object

Import System.Data.OleDb (will be Import System.Data.OleDb (will be System.Data.SQL for SqlServer)System.Data.SQL for SqlServer)

04/20/23 24

Page 25: ADO.NET in VB.NET 2005

Connection ObjectConnection Object

Create the connection to the data sourceCreate the connection to the data source Uses the Connection String InformationUses the Connection String Information

Dim myConnection as New OleDb.Connection Dim myConnection as New OleDb.Connection (connectionString)(connectionString)

04/20/23 25

Page 26: ADO.NET in VB.NET 2005

Data Adapter ObjectData Adapter Object

Table Adapter is Not an Option Here, we Table Adapter is Not an Option Here, we must use a Data Adaptermust use a Data Adapter

Dim myDataAdapter as New OleDbDataAdapter Dim myDataAdapter as New OleDbDataAdapter (“sqlCommand”, connectionObject)(“sqlCommand”, connectionObject)

04/20/23 26

Page 27: ADO.NET in VB.NET 2005

Data Set ObjectData Set Object

Create the Data SetCreate the Data Set

Dim myDataSet as New DataSet Dim myDataSet as New DataSet (“DataSetName”)(“DataSetName”)

Name of DataSet is a String, it must be in Name of DataSet is a String, it must be in Quotation MarksQuotation Marks

04/20/23 27

Page 28: ADO.NET in VB.NET 2005

Data Table ObjectData Table Object

Create the Data TableCreate the Data Table Will Store the Data for the Data Set in Will Store the Data for the Data Set in

Table formTable form

Dim myDataTable as New DataTable Dim myDataTable as New DataTable (“DataTableName”)(“DataTableName”)

Data Table Name is a string, it must be in Data Table Name is a string, it must be in Quotation MarksQuotation Marks

04/20/23 28

Page 29: ADO.NET in VB.NET 2005

Binding SourceBinding Source

You must create a Binding Source Object You must create a Binding Source Object to bind your data controls to the DataSetto bind your data controls to the DataSet

Dim myBindingSource as New Dim myBindingSource as New BindingSourceBindingSource

04/20/23 29

Page 30: ADO.NET in VB.NET 2005

Command BuilderCommand Builder

Fill Command is automatically created for Fill Command is automatically created for the Data Adapter Objectthe Data Adapter Object

In an OleDb Connection a Command Builder In an OleDb Connection a Command Builder object is needed to create the additional object is needed to create the additional commands including Updatecommands including Update

Dim myBuilder as New OldDbCommandBuilder Dim myBuilder as New OldDbCommandBuilder (NameOfDataAdapterObject)(NameOfDataAdapterObject)

04/20/23 30

Page 31: ADO.NET in VB.NET 2005

Sample CodeSample Code

04/20/23 31

Page 32: ADO.NET in VB.NET 2005

Form Load EventForm Load Event

Open the Connection Open the Connection connectionObject.Open( )connectionObject.Open( )

Add the DataTable to the DataSetAdd the DataTable to the DataSet dataSetObject.Tables.Add(dataTableObject)dataSetObject.Tables.Add(dataTableObject)

Fill the DataSet through the DataAdapterFill the DataSet through the DataAdapter dataAdapterObject.Fill(dataSetObject, dataAdapterObject.Fill(dataSetObject,

“StringName of DataTable”)“StringName of DataTable”) Bind the DataTable to the BindingSourceBind the DataTable to the BindingSource

bindingSourceObject.DataSource = bindingSourceObject.DataSource = dataTableObjectdataTableObject

04/20/23 32

Page 33: ADO.NET in VB.NET 2005

Form Load Events Form Load Events (Con’t)(Con’t)

Bind the Controls to the DataTableBind the Controls to the DataTable Allows Bound Controls to Display Data Allows Bound Controls to Display Data

from DataTablefrom DataTable

controlName.DataBindings.Add (“text”, controlName.DataBindings.Add (“text”, bindingSourceObject, “FieldName”)bindingSourceObject, “FieldName”)

““text” must be typed exactly as seentext” must be typed exactly as seen ““FieldName” is the name of the column FieldName” is the name of the column

from the Data Table – typically the name of from the Data Table – typically the name of the field in the Database (unless an alias is the field in the Database (unless an alias is created by the SQL command)created by the SQL command)

04/20/23 33

Page 34: ADO.NET in VB.NET 2005

Sample CodeSample Code

04/20/23 34

Page 35: ADO.NET in VB.NET 2005

BindingSource ObjectBindingSource Object

BindingSource Object can manipulate BindingSource Object can manipulate through the DataTablethrough the DataTable

CurrencyManager is NOT NeededCurrencyManager is NOT Needed BindingSource.PositionBindingSource.Position BindingSource.CountBindingSource.Count BindingSource.MoveNext( )BindingSource.MoveNext( ) BindingSource.MovePrevious( )BindingSource.MovePrevious( ) BindingSource.MoveFirst( )BindingSource.MoveFirst( ) BindingSource.MoveLast( )BindingSource.MoveLast( )

04/20/23 35

Page 36: ADO.NET in VB.NET 2005

Finalizing UpdateFinalizing Update

EndEdit on the BindingSourceEndEdit on the BindingSource Stops the Editing through the Binding SourceStops the Editing through the Binding SourcebindingSourceObject.EndEdit ( )bindingSourceObject.EndEdit ( )

Update the DataAdapterUpdate the DataAdapter Send Changes back to Original Data SourceSend Changes back to Original Data SourcedataAdapterObject.Update (dataSetObject, dataAdapterObject.Update (dataSetObject,

“stringNameOfDataTable”)“stringNameOfDataTable”)

Close the ConnectionClose the ConnectionconnectionObject.Close ( )connectionObject.Close ( )

04/20/23 36

Page 37: ADO.NET in VB.NET 2005

04/20/23 37

DataGridView classDataGridView class The Windows The Windows

Forms Forms DataGridView DataGridView controlcontrol Provides a Provides a

user interface user interface to ADO.NET to ADO.NET datasetsdatasets

displays displays tabular datatabular data

allows for allows for updates to the updates to the data sourcedata source

Page 38: ADO.NET in VB.NET 2005

Creating DataGridView Creating DataGridView ProgramProgram

Connection ObjectConnection Object DataAdapter ObjectDataAdapter Object DataSet ObjectDataSet Object DataTable ObjectDataTable Object CommandBuilder ObjectCommandBuilder Object

No BindingSource object needed – No BindingSource object needed – Property of DataGridViewProperty of DataGridView

04/20/23 38

Page 39: ADO.NET in VB.NET 2005

Sample CodeSample Code

04/20/23 39

Page 40: ADO.NET in VB.NET 2005

04/20/23 40

Binding the DataGridBinding the DataGrid The DataGrid can receive data from any of The DataGrid can receive data from any of

the following data sources:the following data sources: DataTable class DataTable class DataView class DataView class DataSet class DataSet class DataViewManager class DataViewManager class

dtgObject.DataSource=dataTabledtgObject.DataSource=dataTable

dtgPlayer.DataSource = myPlayerTabledtgPlayer.DataSource = myPlayerTable

Page 41: ADO.NET in VB.NET 2005

Binding the Binding the DataGridViewDataGridView

04/20/23 41

Page 42: ADO.NET in VB.NET 2005

04/20/23 42

Current row and cellCurrent row and cell Users can navigate on the DataGridViewerUsers can navigate on the DataGridViewer CurrentRow.IndexCurrentRow.Index

Holds zero-based integer for highlighted rowHolds zero-based integer for highlighted row CurrentCell propertyCurrentCell property

Gets or sets which cell has the focusGets or sets which cell has the focus Contains DataGridViewCell objectContains DataGridViewCell object

Has ColumnNumber and RowNumber propertiesHas ColumnNumber and RowNumber properties

Item property holds cell content Item property holds cell content ‘‘* display cell contents of third column* display cell contents of third column

Console.WriteLine(dtgTeam.Item(dtgTeam.CurrentRowIndex, Console.WriteLine(dtgTeam.Item(dtgTeam.CurrentRowIndex, 2))2))

Page 43: ADO.NET in VB.NET 2005

04/20/23 43

Data in DataGridViewerData in DataGridViewer Read OnlyRead Only

dtgObject.ReadOnly = TruedtgObject.ReadOnly = True

Storing a column in the DataGridView Storing a column in the DataGridView that you don’t want users to see (eg. that you don’t want users to see (eg. Primary key field)Primary key field)dtgObject.Columns(index).Visible = FalsedtgObject.Columns(index).Visible = False

Page 44: ADO.NET in VB.NET 2005

04/20/23 44

Data Grid Example - Data Grid Example - HomeworkHomework Use Baseball Database (Baseball3.mdb)Use Baseball Database (Baseball3.mdb) DataGridView ExampleDataGridView Example

Create Form with DataGridView ObjectCreate Form with DataGridView Object Create Needed Objects (in Code)Create Needed Objects (in Code) Hidden Column (Primary Key)Hidden Column (Primary Key) TeamID Column – Read OnlyTeamID Column – Read Only

Update Database on Exit ButtonUpdate Database on Exit Button

Bonus: User OpenFileDialog box to Select Bonus: User OpenFileDialog box to Select DatabaseDatabase