SlideShare a Scribd company logo
1 of 17
Download to read offline
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 1 | P a g e
030010401- GUI Programming
Unit-4: ADO.NET Programming
BCA 4th Semester
Note: - This material is prepared by Ms. Preeti P Bhatt. The basic
objective of this material is to supplement teaching and discussion
in the classroom. Student is required to go for extra reading in the
subject through library work.
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 2 | P a g e
Topic Covered
 ADO.NET architecture and its component
 Connected and disconnected architecture
 Working with the DataSet: creating, filling and modifying DataSet, DataGrid control
 Accessing data: Executing query using Command object, reading data using DataReader
 Executing stored procedure
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 3 | P a g e
ADO.NET
ADO.NET is a data access technology from Microsoft .Net Framework , which provides
communication between relational and non-relational systems through a common set of
components.
ADO.NET consists of a set of Objects that expose data access services to the .NET environment.
ADO.NET is built for disconnected architecture, so it enables truly disconnected Data Access
and Data Manipulation through its Dataset Object, which is completely independent from the
Data Source.
ADO.NET provides
• Methods for connecting to data sources
• Retrieving
• Manipulating
• Updating.
ADO.NET Architecture
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 4 | P a g e
Two Main Component of ADO.Net
1. Data Provider
The Data Provider is responsible for providing and maintaining the connection to the
database.
Data Provider is a set of ADO.NET classes that allows you to access specific database,
execute SQL command and retrieve the data.
A data provider is a bridge between your application and a data source.
Four Data Providers for ADO.NET
 OLEDB Provider: (Object Linking and Embedding Database)
o Provides access to any data source that has OLEDB driver.(like Access )
o Namespace : OleDb
 Members provide a direct connection to COM(Component Object
Model)-based OLE DB data providers for databases and data
sources other than SQL Server and Oracle.
 ODBC Provider: (Open Database Connectivity)
o Provides access to any data source that has an ODBC driver.
o Namespace : ODBC
 Members provide connectivity to legacy data sources that don’t
have OLE DB data providers.
 SQLServer Provider: provides access to SQL server database
o Namespace : SqlClient
 Members provide high performance connectivity to SQL Server.
 Oracle Provider: provides access to Oracle database.
o Namespace : SqlClient
 Members deliver functionality similar to SqlClient for Oracle
databases.
How to Import Namespace?
Sql Example
Imports System.Data ‘For dataset object
Imports System.Data.SQLClient ‘For data provider object
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 5 | P a g e
Object of data provider
The four Objects from the .Net Framework provide the functionality of Data Providers
in ADO.NET.
 Connection Object
 Command
 Data Reader
 Data Adapter
Connection
Connection class allows you to establish a connection to data source.
The connection string is a series of name/value setting separate by semicolon (;)
The few information required in connection string are
 Server where database is located
 Database you want to use
 Database should authenticate you
Connections can be opened in two ways:
 Explicitly by calling the Open method on the connection
 Implicitly when using a DataAdapter.
When creating a connection object you can pass the connection string as a constructor
parameter.
You can also set the ConnectionString property by hand.
Ex: connection with SqlClient
 Without argument constructor
Dim connection as new SqlConnection()
connection.ConnectionString= “Connection String"
 With Argument constructor
Dim connection As SqlConnection
Connection = New SqlConnection ("Connection String")
Common properties and methods
Method/Property Use
Open() open the connection
Close() Close the connection()
ConnectionString The string use to make connection with database
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 6 | P a g e
Command
The command class allows you to execute any type of SQL Command.
You can also use command class to perform user defined task such as create table,
alter table etc.
Example:
Dim cnn As SqlConnection
Dim cmd As SqlCommand
cnn = New SqlConnection(“ConnectionString”)
cmd = New SqlCommand("Your SQL Statement Here", cnn)
Property of Command Object
o Connection
o CommandType
o CommandText
o Parameters
Methods for execute commands on the database:
● ExecuteNonQuery: Executes commands that have no return values such as
INSERT, UPDATE or DELETE
● ExecuteScalar: Returns a single value from a database query.
● ExecuteReader: Returns a result set by way of a DataReader object.
Data Reader
DataReader Object in ADO.NET is a stream-based, forward-only, read-only retrieval of
query results from the Data Source, which do not update the data.
The DataReader cannot be created directly from code; they created only by calling the
ExecuteReader method of a Command Object.
Dim cmd As SqlCommand(“Query”, con)
Dim DataReader As new SqlDataReader
DataReader = Command.ExecuteReader()
Common methods of DataReader
o Read() : It is used to read the rows from DataReader and it always moves
forward to a new valid row, if any row exist .
o Close() : it used to close dataReader connection with database.
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 7 | P a g e
Data Adapter
DataAdapter is a part of the ADO.NET Data Provider. DataAdapter provides the
communication between the Dataset and the Datasource.
We can use the DataAdapter in combination with the DataSet Object. That is these two
objects combine to enable both data access and data manipulation capabilities.
The DataAdapter can perform Select, Insert, Update and Delete SQL operations in the
Data Source.
The Insert, Update and Delete SQL operations, we are using the continuation of the
Select command perform by the DataAdapter.
That is the DataAdapter uses the Select statements to fill a DataSet and use the other
three SQL commands (Insert, Update, delete) to transmit changes back to the
Database.
Example: Using Command Object
Dim sqlCmd As SqlCommand
Dim adapter As SqlDataAdapter
Dim ds As New DataSet
sqlCmd = New SqlCommand(“Your Select Query”, sqlCnn)
adapter = New SqlDataAdapter(cmd)
adapter.Fill(ds)
Example: Without using Command Object
Dim adapter As SqlDataAdapter
Dim ds As New DataSet
adapter = New SqlDataAdapter(“Your Select Query”, sqlCnn)
adapter.Fill(ds)
Methods of DataAdapter
 Fill()
 FillSchema()
 Update()
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 8 | P a g e
2. DataSet : Second component of ADO.Net
The DataSet is the heart of disconnected data access.
The ADO.NET DataSet contains DataTableCollection and their DataRelationCollection .
It represents a collection of data retrieved from the Data Source. We can use Dataset in
combination with DataAdapter class.
The DataSet object offers disconnected data source architecture. The Dataset can work
with the data it contains, without knowing the source of the data coming from. That is,
the Dataset can work with a disconnected mode from its Data Source.
It gives a better advantage over DataReader , because the DataReader is working only
with the connection oriented Data Sources.
Example
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim i As Integer
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Your SQL Statement Here"
connection = New SqlConnection(connetionString)
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 9 | P a g e
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
connection.Close()
For i = 0 To ds.Tables(0).Rows.Count - 1
MsgBox(ds.Tables(0).Rows(i).Item(0) & " -- " &
ds.Tables(0).Rows(i).Item(1))
Next
Catch ex As Exception
MsgBox("Cannot open connection ! ")
End Try
End Sub
End Class
Connected and Disconnected Architecture
The ADO.NET Framework supports two models of Data Access Architecture,
 Connection Oriented Data Access Architecture
 Disconnected Data Access Architecture.
Connection Oriented Data Access
In Connection Oriented Data Access Architecture the application makes a connection to the
Data Source and then interacts with it through SQL requests using the same connection.
In these cases the application stays connected to the database system even when it is not using
any Database Operations.
Connected Environment (Scenario)
1. Open connection
2. Execute command
3. Process rows in reader
4. Close reader
5. Close connection
Working with data directly via open connection
Advantages Drawbacks
 Simple security realization
 Work with real data
 Simple organization of distributed work
 Continual connection
 Not available via Internet
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 10 | P a g e
Disconnection Oriented Data Access
ADO.Net solves connection problem by introduces a new component called Dataset.
The DataSet is the central component in the ADO.NET Disconnected Data Access Architecture.
A DataSet is an in-memory data store that can hold multiple tables at the same time.
Datasets only hold data and do not interact with a Data Source.
Disconnected Environment (Scenario)
1. Open connection
2. Fill the DataSet
3. Close connection
4. Process the DataSet
5. Open connection
6. Update the data source
7. Close connection
Accessing data: Executing query using Command object, reading data
using DataReader
 Executing query using Command object
 Insert
 Update
 Delete
 Select
 Reading data using DataReader
 While select query is used
Example: Executing Query using command Object and DataSet
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 11 | P a g e
Imports System.Data.SqlClient
Public Class Form1
Dim con As New SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=
D:DotNetProgramming 2013VB.NetProgramDemoSQLConnectivitySQLConnectivity
EMP.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")
Dim cmd As New SqlCommand()
Dim ad As New SqlDataAdapter()
Dim ds As New DataSet
Dim i As Integer
‘Code For Insert Query
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnSave.Click
Try
con.Open()
cmd = New SqlCommand("insert into emp_info values
(@id,@name,@desg,@salary)",con)
cmd.Parameters.AddWithValue("@id", Convert.ToInt32(txtId.Text))
cmd.Parameters.AddWithValue("@name", txtName.Text)
cmd.Parameters.AddWithValue("@desg", cbDsgn.SelectedItem)
cmd.Parameters.AddWithValue("@salary", Convert.ToInt32(txtSal.Text))
i = cmd.ExecuteNonQuery()
MsgBox("Data Inserted")
display()
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
End Sub
‘Code For Delete Query
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnDelete.Click
Try
con.Open()
cmd = New SqlCommand("delete from emp_info where id=@id", con)
cmd.Parameters.AddWithValue("@id", Convert.ToInt32(txtId.Text))
i = cmd.ExecuteNonQuery()
MsgBox("Data deleted")
display()
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
End Sub
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 12 | P a g e
Public Sub display()
ds.Clear()
ad = New SqlDataAdapter("select * from emp_info ", con)
ad.Fill(ds, "Temp")
dataGrid.DataSource = ds
dataGrid.DataMember = "Temp"
End Sub
‘Code For Select Query
Private Sub btnSelect_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnSelect.Click
con.Open()
display()
con.Close()
End Sub
‘Code For Update Query
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnUpdate.Click
Try
con.Open()
cmd = New SqlCommand("update emp_info set name=@name, designation=@desg,
salary=@salary where id=@id", con)
cmd.Parameters.AddWithValue("@id", Convert.ToInt32(txtId.Text))
cmd.Parameters.AddWithValue("@name", txtName.Text)
cmd.Parameters.AddWithValue("@desg", cbDsgn.SelectedItem)
cmd.Parameters.AddWithValue("@salary", Convert.ToInt32(txtSal.Text))
i = cmd.ExecuteNonQuery()
MsgBox("Data Updated")
display()
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
End Sub
‘Code For cell selection in gridview
Private Sub dataGrid_CellClick(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.DataGridViewCellEventArgs) Handles dataGrid.CellClick
Dim r As Integer
r = dataGrid.CurrentCell.RowIndex
txtId.Text = dataGrid.Rows(r).Cells(0).Value
txtName.Text = dataGrid.Rows(r).Cells(1).Value
cbDsgn.SelectedItem = dataGrid.Rows(r).Cells(2).Value
txtSal.Text = dataGrid.Rows(r).Cells(3).Value
End Sub
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 13 | P a g e
‘Code For Select Query
Sub Navigate()
Dim r As Integer
r = Me.BindingContext(ds, "Temp").Position
txtId.Text = dataGrid.Rows(r).Cells(0).Value
txtName.Text = dataGrid.Rows(r).Cells(1).Value
cbDsgn.SelectedItem = dataGrid.Rows(r).Cells(2).Value
txtSal.Text = dataGrid.Rows(r).Cells(3).Value
End Sub
Private Sub btnCurrent_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnCurrent.Click
Navigate()
End Sub
Private Sub btnLast_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnLast.Click
Me.BindingContext(ds, "Temp").Position = Me.BindingContext(ds,
"Temp").Count - 1
Navigate()
End Sub
Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnNext.Click
Me.BindingContext(ds, "Temp").Position = Me.BindingContext(ds,
"Temp").Position + 1
Navigate()
End Sub
Private Sub btnPrevious_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnPrevious.Click
Me.BindingContext(ds, "Temp").Position = Me.BindingContext(ds,
"Temp").Position - 1
Navigate()
End Sub
Private Sub btnFirst_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnFirst.Click
Me.BindingContext(ds, "Temp").Position = 0
Navigate()
End Sub
End Class
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 14 | P a g e
Example: Reading data using DataReader
DataGrid Control
The DataGridView can display data in
 Bound mode – Static Binding- Directly from Gridview
 Bound mode is suitable for managing data using automatic interaction with the
data store.
 One very common use of the DataGridView control is binding to a table in a
database.
 Unbound mode – Dynamic Binding (Using Code)
 Unbound mode is suitable for displaying relatively small amounts of data that
you manage programmatically.
To bind GridView we can use two properties
 DataSource— It gets or sets DataSource that the DataGridView is displaying data.
 The data source, typically a dataset
 DataMember— It get or set the name of the table in the DataSource for which the
DataGridView is display data.
Example:
DataGridView1.DataSource = dataset Object
DataGridView1.DataMember = “Student"
Dim con As New SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=D:
DotNetProgramming 2013VB.NetProgram
DemoSQLConnectivitySQLConnectivityEMP.mdf;
Integrated Security=True;Connect Timeout=30;User
Instance=True")
Dim cmd As New SqlCommand()
Dim dr As SqlDataReader
cmd = New SqlCommand("select * from emp_info ", con)
dr = cmd.ExecuteReader()
While dr.Read()
MsgBox(dr(0) & " , " & dr(1) & " , " & dr(2) & " , " & dr(3))
End While
dr.Close()
con.Close()
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 15 | P a g e
Working with the Dataset:
 Dataset is a disconnected, in-memory representation of the data.
 It can be consider as local copy of portion of database.
 It can be manipulated and updated independent of the database.
 Creating, filling and modifying DataSet
o Create object of dataset
o Create DataTable object
o Create DataColumn object
o Add Column in DataTable
o Create DataTable row
o Assign value in each column
o Add DataTable in DataSet
Example
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim idCoulumn As DataColumn
Dim nameCoulumn As DataColumn
dt = New DataTable()
dt.TableName = "Data"
idCoulumn = New DataColumn("ID", Type.GetType("System.Int32"))
nameCoulumn = New DataColumn("Name", Type.GetType("System.String"))
dt.Columns.Add(idCoulumn)
dt.Columns.Add(nameCoulumn)
dr = dt.NewRow()
dr("ID") = 1
dr("Name") = "Name1"
dt.Rows.Add(dr)
dr = dt.NewRow()
dr("ID") = 2
dr("Name") = "Name2"
dt.Rows.Add(dr)
ds.Tables.Add(dt)
End Sub
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 16 | P a g e
Executing stored procedure
The data provider is a set of components that include the Connection, Command, DataReader,
and DataAdapter Objects.
The command Object provides a number of Execute methods that can be used to perform the
SQL queries in a variety of fashions.
A stored procedure is a precompiled executable object that contains one or more SQL
statements. A sample Stored Procedure is given below:
CREATE PROCEDURE Procedure_name
AS
Procedure Command
GO
Example
CREATE PROCEDURE SPPUBLISHER
AS
SELECT PUB_NAME FROM publishers
GO
The above code creates a procedure named as 'SPPUBLISHER' and it execute SQL statement
that selects all publisher names from publishers table from the PUB database.
Using stored procedures, database operations can be encapsulated in a single command,
optimized for best performance, and enhanced with additional security.
To call a stored procedure from VB.NET application, set the CommandType of the Command
object to StoredProcedure.
Command.CommandText=”StoreProcedure Name”
command.CommandType = CommandType.StoredProcedure
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 17 | P a g e
From the following source code you can see how to call a stored procedure from VB.NET
application.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim command As New SqlCommand
Dim ds As New DataSet
Dim i As Integer
connetionString = "Data Source=servername;Initial
Catalog=PUBS;User ID=sa;Password=yourpassword"
connection = New SqlConnection(connetionString)
connection.Open()
command.Connection = connection
command.CommandType = CommandType.StoredProcedure
command.CommandText = "SPPUBLISHER"
adapter = New SqlDataAdapter(command)
adapter.Fill(ds)
For i = 0 To ds.Tables(0).Rows.Count - 1
MsgBox(ds.Tables(0).Rows(i).Item(0))
Next
connection.Close()
End Sub
End Class

More Related Content

What's hot

Ado.net & data persistence frameworks
Ado.net & data persistence frameworksAdo.net & data persistence frameworks
Ado.net & data persistence frameworksLuis Goldster
 
Vb.net session 05
Vb.net session 05Vb.net session 05
Vb.net session 05Niit Care
 
Intake 38 data access 1
Intake 38 data access 1Intake 38 data access 1
Intake 38 data access 1Mahmoud Ouf
 
Intake 38 data access 4
Intake 38 data access 4Intake 38 data access 4
Intake 38 data access 4Mahmoud Ouf
 
Database programming in vb net
Database programming in vb netDatabase programming in vb net
Database programming in vb netZishan yousaf
 
Ado.Net Architecture
Ado.Net ArchitectureAdo.Net Architecture
Ado.Net ArchitectureUmar Farooq
 
Database connectivity to sql server asp.net
Database connectivity to sql server asp.netDatabase connectivity to sql server asp.net
Database connectivity to sql server asp.netHemant Sankhla
 
Ado.net session04
Ado.net session04Ado.net session04
Ado.net session04Niit Care
 
ADO.NET difference faqs compiled- 1
ADO.NET difference  faqs compiled- 1ADO.NET difference  faqs compiled- 1
ADO.NET difference faqs compiled- 1Umar Ali
 
Ado.net session02
Ado.net session02Ado.net session02
Ado.net session02Niit Care
 
Understanding C# in .NET
Understanding C# in .NETUnderstanding C# in .NET
Understanding C# in .NETmentorrbuddy
 

What's hot (20)

Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
 
ADO.NET -database connection
ADO.NET -database connectionADO.NET -database connection
ADO.NET -database connection
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
Intake 38 10
Intake 38 10Intake 38 10
Intake 38 10
 
Ado.net & data persistence frameworks
Ado.net & data persistence frameworksAdo.net & data persistence frameworks
Ado.net & data persistence frameworks
 
Ado.net
Ado.netAdo.net
Ado.net
 
Ado.net
Ado.netAdo.net
Ado.net
 
Vb.net session 05
Vb.net session 05Vb.net session 05
Vb.net session 05
 
Intake 38 data access 1
Intake 38 data access 1Intake 38 data access 1
Intake 38 data access 1
 
Chap14 ado.net
Chap14 ado.netChap14 ado.net
Chap14 ado.net
 
Intake 38 data access 4
Intake 38 data access 4Intake 38 data access 4
Intake 38 data access 4
 
Ado.net
Ado.netAdo.net
Ado.net
 
Database programming in vb net
Database programming in vb netDatabase programming in vb net
Database programming in vb net
 
Ado.Net Architecture
Ado.Net ArchitectureAdo.Net Architecture
Ado.Net Architecture
 
Database connectivity to sql server asp.net
Database connectivity to sql server asp.netDatabase connectivity to sql server asp.net
Database connectivity to sql server asp.net
 
Ado.net session04
Ado.net session04Ado.net session04
Ado.net session04
 
Database Connection
Database ConnectionDatabase Connection
Database Connection
 
ADO.NET difference faqs compiled- 1
ADO.NET difference  faqs compiled- 1ADO.NET difference  faqs compiled- 1
ADO.NET difference faqs compiled- 1
 
Ado.net session02
Ado.net session02Ado.net session02
Ado.net session02
 
Understanding C# in .NET
Understanding C# in .NETUnderstanding C# in .NET
Understanding C# in .NET
 

Viewers also liked

Viewers also liked (7)

Ch6
Ch6Ch6
Ch6
 
Unit6
Unit6Unit6
Unit6
 
Unit2
Unit2Unit2
Unit2
 
Unit3
Unit3Unit3
Unit3
 
Unit5
Unit5Unit5
Unit5
 
Arrive RoomPoint
Arrive RoomPointArrive RoomPoint
Arrive RoomPoint
 
Unit 1 introduction to visual basic programming
Unit 1 introduction to visual basic programmingUnit 1 introduction to visual basic programming
Unit 1 introduction to visual basic programming
 

Similar to Unit4

Similar to Unit4 (20)

Introduction to ado
Introduction to adoIntroduction to ado
Introduction to ado
 
Ado
AdoAdo
Ado
 
Csharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptxCsharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptx
 
Lecture 6. ADO.NET Overview.
Lecture 6. ADO.NET Overview.Lecture 6. ADO.NET Overview.
Lecture 6. ADO.NET Overview.
 
LECTURE 14 Data Access.pptx
LECTURE 14 Data Access.pptxLECTURE 14 Data Access.pptx
LECTURE 14 Data Access.pptx
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
 
5.C#
5.C#5.C#
5.C#
 
unit 3.docx
unit 3.docxunit 3.docx
unit 3.docx
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12
 
Introduction to ado.net
Introduction to ado.netIntroduction to ado.net
Introduction to ado.net
 
2310 b 09
2310 b 092310 b 09
2310 b 09
 
3-ADO.NET.pdf
3-ADO.NET.pdf3-ADO.NET.pdf
3-ADO.NET.pdf
 
ADO .NET by Sonu Vishwakarma
ADO .NET by Sonu VishwakarmaADO .NET by Sonu Vishwakarma
ADO .NET by Sonu Vishwakarma
 
Ado.Net
Ado.NetAdo.Net
Ado.Net
 
ADO.net control
ADO.net controlADO.net control
ADO.net control
 
PPT temp.pptx
PPT temp.pptxPPT temp.pptx
PPT temp.pptx
 
Is2215 lecture7 lecturer_ado_intro
Is2215 lecture7 lecturer_ado_introIs2215 lecture7 lecturer_ado_intro
Is2215 lecture7 lecturer_ado_intro
 
Ado
AdoAdo
Ado
 
Ado .net
Ado .netAdo .net
Ado .net
 
Ado dot net complete meterial (1)
Ado dot net complete meterial (1)Ado dot net complete meterial (1)
Ado dot net complete meterial (1)
 

More from Abha Damani (20)

Ch14
Ch14Ch14
Ch14
 
Ch12
Ch12Ch12
Ch12
 
Ch11
Ch11Ch11
Ch11
 
Ch10
Ch10Ch10
Ch10
 
Ch08
Ch08Ch08
Ch08
 
Ch01 enterprise
Ch01 enterpriseCh01 enterprise
Ch01 enterprise
 
3 data mgmt
3 data mgmt3 data mgmt
3 data mgmt
 
2 it supp_sys
2 it supp_sys2 it supp_sys
2 it supp_sys
 
1 org.perf it supp_appl
1 org.perf it supp_appl1 org.perf it supp_appl
1 org.perf it supp_appl
 
Managing and securing the enterprise
Managing and securing the enterpriseManaging and securing the enterprise
Managing and securing the enterprise
 
Unit2
Unit2Unit2
Unit2
 
Unit 3
Unit 3Unit 3
Unit 3
 
Unit 4
Unit 4Unit 4
Unit 4
 
Unit 5
Unit 5Unit 5
Unit 5
 
Unit 6
Unit 6Unit 6
Unit 6
 
Unit 1
Unit 1Unit 1
Unit 1
 
Language processor
Language processorLanguage processor
Language processor
 
Introduction to compiler
Introduction to compilerIntroduction to compiler
Introduction to compiler
 
Function of device driver
Function of device driverFunction of device driver
Function of device driver
 
Unit 3 assembler and processor
Unit 3   assembler and processorUnit 3   assembler and processor
Unit 3 assembler and processor
 

Recently uploaded

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 

Recently uploaded (20)

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 

Unit4

  • 1. 030010401 BCA 4th Semester Preeti P Bhatt Department of Computer Science, UTU. 1 | P a g e 030010401- GUI Programming Unit-4: ADO.NET Programming BCA 4th Semester Note: - This material is prepared by Ms. Preeti P Bhatt. The basic objective of this material is to supplement teaching and discussion in the classroom. Student is required to go for extra reading in the subject through library work.
  • 2. 030010401 BCA 4th Semester Preeti P Bhatt Department of Computer Science, UTU. 2 | P a g e Topic Covered  ADO.NET architecture and its component  Connected and disconnected architecture  Working with the DataSet: creating, filling and modifying DataSet, DataGrid control  Accessing data: Executing query using Command object, reading data using DataReader  Executing stored procedure
  • 3. 030010401 BCA 4th Semester Preeti P Bhatt Department of Computer Science, UTU. 3 | P a g e ADO.NET ADO.NET is a data access technology from Microsoft .Net Framework , which provides communication between relational and non-relational systems through a common set of components. ADO.NET consists of a set of Objects that expose data access services to the .NET environment. ADO.NET is built for disconnected architecture, so it enables truly disconnected Data Access and Data Manipulation through its Dataset Object, which is completely independent from the Data Source. ADO.NET provides • Methods for connecting to data sources • Retrieving • Manipulating • Updating. ADO.NET Architecture
  • 4. 030010401 BCA 4th Semester Preeti P Bhatt Department of Computer Science, UTU. 4 | P a g e Two Main Component of ADO.Net 1. Data Provider The Data Provider is responsible for providing and maintaining the connection to the database. Data Provider is a set of ADO.NET classes that allows you to access specific database, execute SQL command and retrieve the data. A data provider is a bridge between your application and a data source. Four Data Providers for ADO.NET  OLEDB Provider: (Object Linking and Embedding Database) o Provides access to any data source that has OLEDB driver.(like Access ) o Namespace : OleDb  Members provide a direct connection to COM(Component Object Model)-based OLE DB data providers for databases and data sources other than SQL Server and Oracle.  ODBC Provider: (Open Database Connectivity) o Provides access to any data source that has an ODBC driver. o Namespace : ODBC  Members provide connectivity to legacy data sources that don’t have OLE DB data providers.  SQLServer Provider: provides access to SQL server database o Namespace : SqlClient  Members provide high performance connectivity to SQL Server.  Oracle Provider: provides access to Oracle database. o Namespace : SqlClient  Members deliver functionality similar to SqlClient for Oracle databases. How to Import Namespace? Sql Example Imports System.Data ‘For dataset object Imports System.Data.SQLClient ‘For data provider object
  • 5. 030010401 BCA 4th Semester Preeti P Bhatt Department of Computer Science, UTU. 5 | P a g e Object of data provider The four Objects from the .Net Framework provide the functionality of Data Providers in ADO.NET.  Connection Object  Command  Data Reader  Data Adapter Connection Connection class allows you to establish a connection to data source. The connection string is a series of name/value setting separate by semicolon (;) The few information required in connection string are  Server where database is located  Database you want to use  Database should authenticate you Connections can be opened in two ways:  Explicitly by calling the Open method on the connection  Implicitly when using a DataAdapter. When creating a connection object you can pass the connection string as a constructor parameter. You can also set the ConnectionString property by hand. Ex: connection with SqlClient  Without argument constructor Dim connection as new SqlConnection() connection.ConnectionString= “Connection String"  With Argument constructor Dim connection As SqlConnection Connection = New SqlConnection ("Connection String") Common properties and methods Method/Property Use Open() open the connection Close() Close the connection() ConnectionString The string use to make connection with database
  • 6. 030010401 BCA 4th Semester Preeti P Bhatt Department of Computer Science, UTU. 6 | P a g e Command The command class allows you to execute any type of SQL Command. You can also use command class to perform user defined task such as create table, alter table etc. Example: Dim cnn As SqlConnection Dim cmd As SqlCommand cnn = New SqlConnection(“ConnectionString”) cmd = New SqlCommand("Your SQL Statement Here", cnn) Property of Command Object o Connection o CommandType o CommandText o Parameters Methods for execute commands on the database: ● ExecuteNonQuery: Executes commands that have no return values such as INSERT, UPDATE or DELETE ● ExecuteScalar: Returns a single value from a database query. ● ExecuteReader: Returns a result set by way of a DataReader object. Data Reader DataReader Object in ADO.NET is a stream-based, forward-only, read-only retrieval of query results from the Data Source, which do not update the data. The DataReader cannot be created directly from code; they created only by calling the ExecuteReader method of a Command Object. Dim cmd As SqlCommand(“Query”, con) Dim DataReader As new SqlDataReader DataReader = Command.ExecuteReader() Common methods of DataReader o Read() : It is used to read the rows from DataReader and it always moves forward to a new valid row, if any row exist . o Close() : it used to close dataReader connection with database.
  • 7. 030010401 BCA 4th Semester Preeti P Bhatt Department of Computer Science, UTU. 7 | P a g e Data Adapter DataAdapter is a part of the ADO.NET Data Provider. DataAdapter provides the communication between the Dataset and the Datasource. We can use the DataAdapter in combination with the DataSet Object. That is these two objects combine to enable both data access and data manipulation capabilities. The DataAdapter can perform Select, Insert, Update and Delete SQL operations in the Data Source. The Insert, Update and Delete SQL operations, we are using the continuation of the Select command perform by the DataAdapter. That is the DataAdapter uses the Select statements to fill a DataSet and use the other three SQL commands (Insert, Update, delete) to transmit changes back to the Database. Example: Using Command Object Dim sqlCmd As SqlCommand Dim adapter As SqlDataAdapter Dim ds As New DataSet sqlCmd = New SqlCommand(“Your Select Query”, sqlCnn) adapter = New SqlDataAdapter(cmd) adapter.Fill(ds) Example: Without using Command Object Dim adapter As SqlDataAdapter Dim ds As New DataSet adapter = New SqlDataAdapter(“Your Select Query”, sqlCnn) adapter.Fill(ds) Methods of DataAdapter  Fill()  FillSchema()  Update()
  • 8. 030010401 BCA 4th Semester Preeti P Bhatt Department of Computer Science, UTU. 8 | P a g e 2. DataSet : Second component of ADO.Net The DataSet is the heart of disconnected data access. The ADO.NET DataSet contains DataTableCollection and their DataRelationCollection . It represents a collection of data retrieved from the Data Source. We can use Dataset in combination with DataAdapter class. The DataSet object offers disconnected data source architecture. The Dataset can work with the data it contains, without knowing the source of the data coming from. That is, the Dataset can work with a disconnected mode from its Data Source. It gives a better advantage over DataReader , because the DataReader is working only with the connection oriented Data Sources. Example Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim i As Integer Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString)
  • 9. 030010401 BCA 4th Semester Preeti P Bhatt Department of Computer Science, UTU. 9 | P a g e Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds) adapter.Dispose() command.Dispose() connection.Close() For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " -- " & ds.Tables(0).Rows(i).Item(1)) Next Catch ex As Exception MsgBox("Cannot open connection ! ") End Try End Sub End Class Connected and Disconnected Architecture The ADO.NET Framework supports two models of Data Access Architecture,  Connection Oriented Data Access Architecture  Disconnected Data Access Architecture. Connection Oriented Data Access In Connection Oriented Data Access Architecture the application makes a connection to the Data Source and then interacts with it through SQL requests using the same connection. In these cases the application stays connected to the database system even when it is not using any Database Operations. Connected Environment (Scenario) 1. Open connection 2. Execute command 3. Process rows in reader 4. Close reader 5. Close connection Working with data directly via open connection Advantages Drawbacks  Simple security realization  Work with real data  Simple organization of distributed work  Continual connection  Not available via Internet
  • 10. 030010401 BCA 4th Semester Preeti P Bhatt Department of Computer Science, UTU. 10 | P a g e Disconnection Oriented Data Access ADO.Net solves connection problem by introduces a new component called Dataset. The DataSet is the central component in the ADO.NET Disconnected Data Access Architecture. A DataSet is an in-memory data store that can hold multiple tables at the same time. Datasets only hold data and do not interact with a Data Source. Disconnected Environment (Scenario) 1. Open connection 2. Fill the DataSet 3. Close connection 4. Process the DataSet 5. Open connection 6. Update the data source 7. Close connection Accessing data: Executing query using Command object, reading data using DataReader  Executing query using Command object  Insert  Update  Delete  Select  Reading data using DataReader  While select query is used Example: Executing Query using command Object and DataSet
  • 11. 030010401 BCA 4th Semester Preeti P Bhatt Department of Computer Science, UTU. 11 | P a g e Imports System.Data.SqlClient Public Class Form1 Dim con As New SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename= D:DotNetProgramming 2013VB.NetProgramDemoSQLConnectivitySQLConnectivity EMP.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True") Dim cmd As New SqlCommand() Dim ad As New SqlDataAdapter() Dim ds As New DataSet Dim i As Integer ‘Code For Insert Query Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click Try con.Open() cmd = New SqlCommand("insert into emp_info values (@id,@name,@desg,@salary)",con) cmd.Parameters.AddWithValue("@id", Convert.ToInt32(txtId.Text)) cmd.Parameters.AddWithValue("@name", txtName.Text) cmd.Parameters.AddWithValue("@desg", cbDsgn.SelectedItem) cmd.Parameters.AddWithValue("@salary", Convert.ToInt32(txtSal.Text)) i = cmd.ExecuteNonQuery() MsgBox("Data Inserted") display() Catch ex As Exception MsgBox(ex.Message) End Try con.Close() End Sub ‘Code For Delete Query Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click Try con.Open() cmd = New SqlCommand("delete from emp_info where id=@id", con) cmd.Parameters.AddWithValue("@id", Convert.ToInt32(txtId.Text)) i = cmd.ExecuteNonQuery() MsgBox("Data deleted") display() Catch ex As Exception MsgBox(ex.Message) End Try con.Close() End Sub
  • 12. 030010401 BCA 4th Semester Preeti P Bhatt Department of Computer Science, UTU. 12 | P a g e Public Sub display() ds.Clear() ad = New SqlDataAdapter("select * from emp_info ", con) ad.Fill(ds, "Temp") dataGrid.DataSource = ds dataGrid.DataMember = "Temp" End Sub ‘Code For Select Query Private Sub btnSelect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelect.Click con.Open() display() con.Close() End Sub ‘Code For Update Query Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click Try con.Open() cmd = New SqlCommand("update emp_info set name=@name, designation=@desg, salary=@salary where id=@id", con) cmd.Parameters.AddWithValue("@id", Convert.ToInt32(txtId.Text)) cmd.Parameters.AddWithValue("@name", txtName.Text) cmd.Parameters.AddWithValue("@desg", cbDsgn.SelectedItem) cmd.Parameters.AddWithValue("@salary", Convert.ToInt32(txtSal.Text)) i = cmd.ExecuteNonQuery() MsgBox("Data Updated") display() Catch ex As Exception MsgBox(ex.Message) End Try con.Close() End Sub ‘Code For cell selection in gridview Private Sub dataGrid_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dataGrid.CellClick Dim r As Integer r = dataGrid.CurrentCell.RowIndex txtId.Text = dataGrid.Rows(r).Cells(0).Value txtName.Text = dataGrid.Rows(r).Cells(1).Value cbDsgn.SelectedItem = dataGrid.Rows(r).Cells(2).Value txtSal.Text = dataGrid.Rows(r).Cells(3).Value End Sub
  • 13. 030010401 BCA 4th Semester Preeti P Bhatt Department of Computer Science, UTU. 13 | P a g e ‘Code For Select Query Sub Navigate() Dim r As Integer r = Me.BindingContext(ds, "Temp").Position txtId.Text = dataGrid.Rows(r).Cells(0).Value txtName.Text = dataGrid.Rows(r).Cells(1).Value cbDsgn.SelectedItem = dataGrid.Rows(r).Cells(2).Value txtSal.Text = dataGrid.Rows(r).Cells(3).Value End Sub Private Sub btnCurrent_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCurrent.Click Navigate() End Sub Private Sub btnLast_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLast.Click Me.BindingContext(ds, "Temp").Position = Me.BindingContext(ds, "Temp").Count - 1 Navigate() End Sub Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click Me.BindingContext(ds, "Temp").Position = Me.BindingContext(ds, "Temp").Position + 1 Navigate() End Sub Private Sub btnPrevious_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrevious.Click Me.BindingContext(ds, "Temp").Position = Me.BindingContext(ds, "Temp").Position - 1 Navigate() End Sub Private Sub btnFirst_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFirst.Click Me.BindingContext(ds, "Temp").Position = 0 Navigate() End Sub End Class
  • 14. 030010401 BCA 4th Semester Preeti P Bhatt Department of Computer Science, UTU. 14 | P a g e Example: Reading data using DataReader DataGrid Control The DataGridView can display data in  Bound mode – Static Binding- Directly from Gridview  Bound mode is suitable for managing data using automatic interaction with the data store.  One very common use of the DataGridView control is binding to a table in a database.  Unbound mode – Dynamic Binding (Using Code)  Unbound mode is suitable for displaying relatively small amounts of data that you manage programmatically. To bind GridView we can use two properties  DataSource— It gets or sets DataSource that the DataGridView is displaying data.  The data source, typically a dataset  DataMember— It get or set the name of the table in the DataSource for which the DataGridView is display data. Example: DataGridView1.DataSource = dataset Object DataGridView1.DataMember = “Student" Dim con As New SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=D: DotNetProgramming 2013VB.NetProgram DemoSQLConnectivitySQLConnectivityEMP.mdf; Integrated Security=True;Connect Timeout=30;User Instance=True") Dim cmd As New SqlCommand() Dim dr As SqlDataReader cmd = New SqlCommand("select * from emp_info ", con) dr = cmd.ExecuteReader() While dr.Read() MsgBox(dr(0) & " , " & dr(1) & " , " & dr(2) & " , " & dr(3)) End While dr.Close() con.Close()
  • 15. 030010401 BCA 4th Semester Preeti P Bhatt Department of Computer Science, UTU. 15 | P a g e Working with the Dataset:  Dataset is a disconnected, in-memory representation of the data.  It can be consider as local copy of portion of database.  It can be manipulated and updated independent of the database.  Creating, filling and modifying DataSet o Create object of dataset o Create DataTable object o Create DataColumn object o Add Column in DataTable o Create DataTable row o Assign value in each column o Add DataTable in DataSet Example Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim idCoulumn As DataColumn Dim nameCoulumn As DataColumn dt = New DataTable() dt.TableName = "Data" idCoulumn = New DataColumn("ID", Type.GetType("System.Int32")) nameCoulumn = New DataColumn("Name", Type.GetType("System.String")) dt.Columns.Add(idCoulumn) dt.Columns.Add(nameCoulumn) dr = dt.NewRow() dr("ID") = 1 dr("Name") = "Name1" dt.Rows.Add(dr) dr = dt.NewRow() dr("ID") = 2 dr("Name") = "Name2" dt.Rows.Add(dr) ds.Tables.Add(dt) End Sub
  • 16. 030010401 BCA 4th Semester Preeti P Bhatt Department of Computer Science, UTU. 16 | P a g e Executing stored procedure The data provider is a set of components that include the Connection, Command, DataReader, and DataAdapter Objects. The command Object provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions. A stored procedure is a precompiled executable object that contains one or more SQL statements. A sample Stored Procedure is given below: CREATE PROCEDURE Procedure_name AS Procedure Command GO Example CREATE PROCEDURE SPPUBLISHER AS SELECT PUB_NAME FROM publishers GO The above code creates a procedure named as 'SPPUBLISHER' and it execute SQL statement that selects all publisher names from publishers table from the PUB database. Using stored procedures, database operations can be encapsulated in a single command, optimized for best performance, and enhanced with additional security. To call a stored procedure from VB.NET application, set the CommandType of the Command object to StoredProcedure. Command.CommandText=”StoreProcedure Name” command.CommandType = CommandType.StoredProcedure
  • 17. 030010401 BCA 4th Semester Preeti P Bhatt Department of Computer Science, UTU. 17 | P a g e From the following source code you can see how to call a stored procedure from VB.NET application. Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As SqlDataAdapter Dim command As New SqlCommand Dim ds As New DataSet Dim i As Integer connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword" connection = New SqlConnection(connetionString) connection.Open() command.Connection = connection command.CommandType = CommandType.StoredProcedure command.CommandText = "SPPUBLISHER" adapter = New SqlDataAdapter(command) adapter.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0)) Next connection.Close() End Sub End Class