0% found this document useful (0 votes)
23 views95 pages

Unit-3 ADO - Net Updated

Uploaded by

msself02
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views95 pages

Unit-3 ADO - Net Updated

Uploaded by

msself02
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 95

UNIT – 3

ADO.NET
Outline
 SQL & SQL Syntax
 Benefits of ADO.NET
 Difference between ADO.NET and Classical ADO
 Database connectivity Namespace
 ADO.NET Architecture
 Managed Data Provider
 DataSet
 Connection & Command Object
 Data Adapter Class
 DataSet Class
 DataView Class
 ADO.NET Example
 Connected & Disconnected Mode
 Data Binding
SQL
• Full form of the SQL is structure query language.
• Structure Query Language (SQL) is the language used to manipulate
relational database.
• SQL is tied very closely with the relational model.

 What can SQL Do?


 Execute queries against a database.
 Retrieve data from a database.
 Insert / Update / Delete records in a database.
 Create new databases / tables / stored procedure / views
 Set permission
SQL Syntax
1. Select :
• Retrieves data from one or more tables or views.

 Syntax :
• Select * from TableName; //For all rows and columns
• Select ColumnName from TableName; //For specific column
• Select * from TableName where <condition> //For Particular criteria
• Select * from TableName Order by ColumnName //Order wise

 Example :
• Select * from emp;
• Select Ename , Empno from emp;
• Select * from emp where Empno = 1;
• Select Ename , Empno from emp Order by Ename;
SQL Syntax
2. Insert :
• Creates a new row and inserts values into specified columns.

 Syntax :
• Insert into TableName values (Value1 , Value2 , ….)

 Example :
• Insert into Cat values (1 , ‘Nokia’);
SQL Syntax
3. Update :
• Changes the values of individual columns in one or more existing rows in a
table.

 Syntax :
• Update TableName set columnname = value // For all
• Update Tablename set columnname = value where columnname = value
// For particular row

 Example :
• Update Emp set dal = 1000000;
• Update Product set Pname = ‘NokiaNseries’ , Amt = 5000 where ProductId
= 10;
SQL Syntax
4. Delete :
• Removes one or more rows from a table.

 Syntax :
• Delete from TableName; // Delete all rows
• Delete from Tablename where columnName = value; // Delete
particular row

 Example :
• Delete from product;
• Delete from stu where id = 11;
SQL Syntax
5. Aggregate Function :
• Aggregate functions always return one value.
• There are 5 aggregate function : MAX, MIN, SUM, AVG, COUNT

 Syntax :
• Select AggregateFunName (Columnname) from TableName;

 Example :
• Select Max (sal) from Emp;
• Select Min (sal) from Emp;
• Select Sum (sal) from Emp;
• Select Avg (sal) from Emp;
• Select Count (empno) from Emp;
ADO.NET
• Most applications require some form of data access.
• ADO.NET is a part of the Microsoft .NET Framework.
• The full form of ADO.NET is ActiveX Data Objects.
• ADO.NET has the ability to separate data access mechanism, data
manipulation mechanism and data connectivity mechanism.
• ADO.NET is a set of classes that allows applications to read and write
information in databases.

Our Program ADO.NET Database

• AdO.NET can be used by any .NET language.


ADO.NET
• It’s a concept. It’s not a programming language.
• ADO.NET introduces the concept of disconnected architecture.
• We need to add System.Data namespace for work with ADO.NET.
• It’s a next version of ActiveX Data Objects (ADO) technology which was
used in VB 6.0.
• To work with the database, we need to add namespace.
• using System.Data;
• using System.Data.SqlClient;
Benefits of ADO.NET
1. Interoperability :
• XML is the format for transmitting datasets across the network, so any
component that can read the XML format can process data. In fact, the
receiving component need not to be an ADO.NET component at all.

2. Maintainability :
• When you replace a single tier with two tiers or two tiers with three tiers,
arrange for those tiers to trade information. If the original application is
implemented in ADO.NET using datasets, this transformation is made
easier.

3. Performance :
• ADO.NET provides fast execution of data over ADO model.
Benefits of ADO.NET
4. Programmability :
• ADO.NET provides a very rich API which helps developers to develop
programs more quickly and with fewer mistakes. Typed DataSet provides
safe data and it checks compile time.

5. Scalability :
• ADO.NET provides disconnected mode so there is no problem of
scalability and unlike ADO.NET does not support database locking
concept.
Benefits of ADO.NET
6. Disconnected :
• In connected mode, we make a connection to the Database server and then
interact with it.
• The application stays connected to the Database server even when it is not
using Database services. It is wastes database resource.
• ADO.NET supports disconnected environment it solves this problem by
managing a local buffer of persistent data called DataSet.
• Application automatically connects to the server when it need to pass some
query and then disconnects immediately after getting the result back and
storing it in dataset.
Compare ADO.NET to Classic ADO
Difference ADO ADO.NET
Data Access Connection Model Disconnected model
Locking Supports Does not support
XML Support Limited Robust
Format of Data Transferring COM based XML for transferring data
to and from your database
and web application.
Data Provide Record Set DataSet and Data Adapter
Data Persistent Stores the data in the XML Stores the data in the
format. binary format.
Tables Record set, is like a single Data Set can contain
table or query result. multiple tables.
Cursor Supports Does not support
Connection Client application need to Client disconnected as
be connected to data soon as the data is fetched
server while working on or processed.
data.
Database Connectivity Namespaces
1. System.Data :
• It provides database independent classes and DataSet, DataTable,
DataRow, DataColumn and DataRelation Classes.

2. System.Data.Common :
• It provides data provider classes such as System.Data.SqlClient,
System.Data.Oledb, System.Data.OracleClient etc..

3. System.Data.OleDB(Object Linking and Embedding DB) :


• It is collection of classes such as OledbConnection, OledbCommand,
OledbDataReader, etc.. It use when backend datas Microsoft Access or
Excel, etc..
Database Connectivity Namespaces
4. System.Data.SqlClient :
• It is collection of classes such as SqlConnection, SqlCommand,
SqlDataReader, etc.. It use when backend data as Sqlserver.

5. System.Data.OracleClient :
• It is collection of classes such as OracleConnection, OracleCommand,
OracleDataReader, etc.. It use when backend data as Oracle.

6. System.Data.SqlTypes :
• Provide classes that are SQL server specific data types such as SqlBinary,
SqlBoolean, SqlByte, SqlChar, SqlDateTime, SqlDecimal, SqlFileStream,
SqlInt16, SqlInt64, SqlMoney, SqlSingle, SqlString, SqlXml.
Database Connectivity Ways
 Connected :
• Client uses data from Database directly not from Dataset so Database
connectivity is upto client closes form.

Fetch
Data
Command
Reader
Data Connection

Return Data
Application

DataBase
Database Connectivity Ways
 Disconnected :
• Data stored into Dataset and client uses data from Dataset only so Database
connectivity for fraction of minute.

Data Adapter
Fill Data

Data Select Command


Set
Insert Command
Connection
Application
Update Command

Update Data Delete Command

Database
Disconnected Data Access Connected Data Access
ADO.NET Architecture
Data Set
Connection
Data Table Collection
Transaction Data Adapter
Data Table
Select Command
Data Row Collection
Command
Insert Command
Data Row Collection
Parameters
Update Command
Data Row Collection
Delete Command
Data Reader
Data Relation Collection

Database XML
ADO.NET Architecture
• There are two major components of ADO.NET.

DATA SET DATA PROVIDER

ADO.NET
ADO.NET Architecture
 Data Set :
• Data Set represents either an entire database or a subset of database. It can
contain tables and relationship between those tables.

 Data Provider :
• Data Provider is a collection of components like Connection, Command,
DataReader, DataAdapter objects and handles communication with a
physical data store and the database.
Managed Data Provider
• The Data Provider is responsible for providing and maintaining the
connection to the database.
• It is a set of classes that can be used for communicating with database, and
holding / manipulating data.
• The Data provider connects to the data source on behalf of ADO.NET.
• The data source can be Microsoft SQL server or Oracle database and
OLEDB data provider.
• The Data provider components are specific to data source.
• The data provider consists of the following four objects :
1. Connection
2. Command
3. Data Reader
4. Data Adapter
Managed Data Provider
1. Connection :
• It establishes or connects a connection to the data source.
• The base class of all connection object is DbConnection class.
• The Connection object has the methods for opening and closing connection
and beginning a transaction.
• The Connection object has the properties for setting the timeout property
period of connection.
• The .NET Framework provides four types of Connection classes, namely
SqlConnection, OleDbConnection, OdbcConnection, and
OracleConnection.
• These are designed specifically to connect to provide connections to a wide
range of database, such as MS-Excel and Oracle.
Managed Data Provider
2. Command :
• It fires SQL commands or perform some action on the data source, such as
insert, update and delete.
• Execute a command against the data source and retrieve a DataReader or
Dataset.
• The base class for all command object is the DbCommand class.
• The command object is represented by two classes : SqlCommand and
OleDbCommand
• The ExecuteQuery() method executes the command, such as INSERT,
UPDATE or DELETE that have no return value.
• The ExecuteScalar() method return a single value from a database query.
• The ExecuteReader() method returns a result set through the DataReader
object.
Managed Data Provider
3. Data Reader :
• Used when large list of results one record at time. It reads records in a
read-only forward-only methods.
• The base class of all DataReader objects is the DbDataReader class.
• The DataReader object cannot be directly instantiated.
Managed Data Provider
4. Data Adapter :
• It’s a bridge between DataSource and DataSet object for transferring data.
• Update the Dataset with data from the data source.
• The base class for all the DataAdapter objects is the DbDataAdapter
class.
• It used to fill a DataTable or Dataset with data from database using Fill()
method.
• The DataAdapter object commits the changes to the database by calling the
Update() method.
• It also provides four properties that represent the database command, that
is SelectCommand, InsertCommand, DeleteCommand and
UpdateCommand.
ADO.NET Data Provider
For SQL Imports System.Data.SqlClient namespaces.
Server It provides data access for Microsoft SQL Server.

For Imports System.Data.OleDb namespaces.


OLEDB It provides data sources exposed using OLE DB.

For Imports System.Data.Odbc namespaces.


ODBC It provides data sources exposed using ODBC.

For Imports System.Data.OracleClient namespaces.


Oracle It provides data access for Oracle.
Data Set / Other ADO.NET Objects
1. Data View Object :
• Data view works with the Data Table.
• With the help of DataView can be create different views of the data stored
in a DataTable, a capability that is often used in data binding applications.
• Important properties of DataView are RowFilter and Count and
methodSort.
• DataView does not affect the actual data store in the DataTable.

 Example :
DataView dv = new DataView();
dv.RowFilter = “Rno = ” + textBox1.Text;
dv.Sort = “Ename Desc”;
MessageBox.Show ( dv.Count.ToString() );
Data Set / Other ADO.NET Objects
2. Data Table Object :
• Data Set contains Data Table.
• A Data Table object represents a database table.
• It is a collection of Columns and Rows. It is a part of Data Set.
• Data Table represents a single table.

 Example :
ds.Tables[“Emp”]
ds.Table[0]
ds.Tables[0].Rows.Count
ds.Tables[0].Columns.Count
Data Set / Other ADO.NET Objects
3. Constraint Object :
• A constraint means rules and regulation.
• It is used to maintain the integrity of the data in the Data Table.
• A constraint class have three types of constraints :
1. Unique key constraint
2. Foreign key constraint
3. Primary key constraint
• The difference between unique and primary key constraints is unique
allows null and primary does not.
• Foreign key constraints dives surety about changes in master table affects
child table.
Data Set / Other ADO.NET Objects
4. DataRelation Object :
• It represents parent child relationship.
• We can create parent child data relations between Data Table using
DataRelation Object.
• Represents a parent / child relationship between two Data Table objects.
• ADO.NET Data Table object maintains a collection of Constraints.
• Each record is identified by matrix form row X column.
Data Set / Other ADO.NET Objects
5. DataRow Object :
• It represents row of the table.
• The Rows property of the DataTable object represents the
DataRowCollection, which is a collection of DataRow objects in a Data
Table.
• Each Data Row object represent a single record in a table that has been
retrieved from the data source.

6. DataColumn Object :
• It represents column of the Table.
• The Column property of the Data Table object represents the
DataColumnCollection, which is a collection of DataColumn objects in a
DataTable.
Connection Object
• The Connection object creates the connection to the database.
• The connection object represents the physical connection to a data source.
• The Connection object contains all of the information required to open a
connection to the database.

 Basic Steps :
1. Create Database
2. Create connection object
3. Set the Provider
4. Specify the data source
ConnectionString Property
• A connection string has a group of semi-colon separated attributes.
• Every .NET Data Provider connection string looks different; depending on
the type of .NET Data Provider you need to use and which attributes are
set for each different type of database system.

SqlConnection conn = new SqlConnection (“Data Source = .\\


SQLEXPRESS; AttachDbFilename = D:\\DbEMPLOYE.mdf; Integrated
Security = True”)

Keyword Description
Data Source Server Name or network address of SQL Server
AttachDbFilename Name of the database
Integrated Security Whether the connection is a secure Connection
Methods of Connection Object
1. Open :
• It opens the connection to our database.

2. Close :
• It closes the database connection.

3. Dispose :
• It release the resources on the connection object.

4. State :
• Returns 0 for not connected or 1 for connected.
• Return state of connection object.
Command Object
• It’s depends on Connection object.
• Command objects are used to execute commands to a database across a
data connection.
• The Command Object in ADO.NET executes SQL statements and Stored
Procedures against the data source specified in the Connection Object.
• Command objects can support SQL statements and stored procedures that
can return single values; one or more sets of rows or no values at all.
• The Command Object has a property called CommandText, which contains
a String (Query) value that represents the command that will be executed
in the Data Source.
Properties of Command Object
1. Connection Property :
• This property contains data about the connection string. It must be set on
the SqlCommand object before it is executed.
• For the command to execute properly, the connection must be open at the
time of execution.

string str = “Select * from emp ”;


SqlConnection conn = new SqlConnection (“Data Source = .\\SQLEXPRESS;
AttachDbFilename = D:\\DbGMIT.mdf; Integrated Security = True”)
SqlCommand cmd = new SqlCommand ();
cmd.Connection = conn;

string str = “Select * from emp ”;


SqlConnection conn = new SqlConnection (“Data Source = .\\SQLEXPRESS;
AttachDbFilename = D:\\DbGMIT.mdf; Integrated Security = True”)
SqlCommand cmd = new SqlCommand (str , conn);
Properties of Command Object
2. CommandText Property :
• This property specifies the SQL string or the Stored Procedure.
• Using SQL String

string str = “Select * from emp ”;


SqlConnection conn = new SqlConnection (“Data Source = .\\SQLEXPRESS;
AttachDbFilename = D:\\DbGMIT.mdf; Integrated Security = True”)
SqlCommand cmd = new SqlCommand (str , conn);

string str = “Select * from emp ”;


SqlConnection conn = new SqlConnection (“Data Source = .\\SQLEXPRESS;
AttachDbFilename = D:\\DbGMIT.mdf; Integrated Security = True”)
SqlCommand cmd = new SqlCommand ( );
cmd.Connection = conn ;
cmd.CommandText = str ;
Properties of Command Object
• Using Stored Procedure

CREATE PROCEDURE [dbo] [Emp_Select]


AS Select * from Emp
RETURN 0

• Calling :

SqlCommand cmd = new SqlCommand ( );


cmd.Connection = conn ;
cmd.CommandType = CommandType.StoredProcedure ;
cmd.CommandText = “Emp_Select”;
Properties of Command Object
3. Command Type Property

cmd.ComandType =
CommandType.StoredProcedure
CommandType.TableDirect
CommandType.Text

Command Type Description

Stored Procedure When we want to work with stored


procedure
Table Direct Table Name

Text (Default) SQL queries directly


Method of Command Object
• Command object has three important methods for execute queries.
• To execute any method needs open connection.

• Connection should be open for the below methods :


1. ExecuteScalar
2. ExecuteNonQuery
3. ExecuteReader
ExecuteScalar
• It’s used with Aggregate functions.
• There are 5 aggregate functions Max, Min, Avg, Sum and Count.
• It returns only one value at a time.
• It fetches the data from the Database.

Max Sal 19000 Min Sal 2000

Avg Sal 8090.0000 Sum Sal 80900

Count Emp 10

Answer
ExecuteScalar Example
private void button1_click(object sender , EventAgrs e)
{
SqlConnection conn = new SqlConnection (“Data Source = .\\
SQLEXPRESS; AttachDbFilename = D:\\DbGMIT.mdf; Integrated Security =
True”)
SqlCommand cmd = new SqlCommand( );
cmd.Connection = conn;
string str = “Select Max(Salary) from emp”; //Max
cmd.ComamndText = str;

conn.Open( );
txtMaxSal.Text = cmd.ExecuteScalar().ToString();
conn.Close();
ExecuteScalar Example
str = “Select Min(Salary) from emp”; //Min
cmd.ComamndText = str;

conn.Open( );
txtMinSal.Text = cmd.ExecuteScalar().ToString();
conn.Close();

str = “Select Avg(Salary) from emp”; //Avg


cmd.ComamndText = str;

conn.Open( );
txtAvgSal.Text = cmd.ExecuteScalar().ToString();
conn.Close();
ExecuteScalar Example
str = “Select Sum(Salary) from emp”; //Sum
cmd.ComamndText = str;

conn.Open( );
txtSumSal.Text = cmd.ExecuteScalar().ToString();
conn.Close();

str = “Select Count(*) from emp”; //Count


cmd.ComamndText = str;

conn.Open( );
txtCntEmp.Text = cmd.ExecuteScalar().ToString();
conn.Close();
ExecuteNonQuery
• To Execute Insert, Update, Delete queries.
• It returns number of rows affected.

Enter Std 1

Answer

Total Record Deleted = 5

OK
ExecuteScalar Example
private void button1_click(object sender , EventAgrs e)
{
int total = 0;
SqlConnection conn = new SqlConnection (“Data Source = .\\
SQLEXPRESS; AttachDbFilename = D:\\DbGMIT.mdf; Integrated Security =
True”)
SqlCommand cmd = new SqlCommand( );
cmd.Connection = conn;
cmd.CommandText = “Delete from Stu where Std = ” + txtStd.Text;
conn.Open( );
total = cmd.ExecuteNonQuery( );
conn.Close();
MessageBox.Show(“Total Record Deleted = ” + total);
}
ExecuteReader
• When we execute the command object using ExecuteReader method that
time it returns DataReader.
• It returns DataReader which represents forward and readonly records.
• DataReader is used to retrieve a read-only, forward-only stream of data
from a database.
• We can not perform any insert, update and delete operations in the
DataReader.
• DataReader is opposite of DataSet.
• We can not move previous in the DataReader.
• When we just want to fill the data that time use DataReader.
• DataReader requires open connection.
• DataReader can hold one table at a time.
• DataReader have Item Collection.
ExecuteReader
• DataReader can increase application performance both by retrieving data
as soon as it is available, and (by default) storing only one row at a time in
memory, reducing system overhead.
• For example, Select Empno, Ename, Age from Emp then Empno is dr[0],
Ename is dr[1] and Age is dr[2].
• DataReader have read method to read next record.
• DataReader is set by command object’s ExecuteReader method.

SNo 7

SName Ritu
ExecuteReader Example
private void frmReader_Load(object sender , EventAgrs e)
{
SqlConnection conn = new SqlConnection (“Data Source = .\\
SQLEXPRESS; AttachDbFilename = D:\\DbGMIT.mdf; Integrated Security =
True”)
SqlCommand cmd = new SqlCommand( );
SqlDataReader dr;
cmd.Connection = conn;
cmd.CommandText = “Select * from Stu”;
conn.Open( );
dr = cmd.ExecuteReader( );
ExecuteReader Example
while ( dr.Read() )
{
cmbSNo.Items.Add( dr[“SNo”].ToString() );
cmbSName.Items.Add( dr[“SName”].ToString() );
}
conn.close();
}
private void cmbSNo_SelectedIndexChanged(object sender , EventArgs e)
{
cmbSName.SelectedIndex = cmbSNo.SelectedIndex;
}
private void cmbSName_SelectedIndexChanged(object sender , EventArgs e)
{
cmbSNo.SelectedIndex = cmbSName.SelectedIndex;
}
DataAdapter Class
• It is associated Command and Connection objects.
• The DataAdapter is the class at the core of ADO.NET disconnected data
access.
• It is the middleman or bridge between the Database and a DataSet.
• The DataAdapter provides a set of methods and properties to retrieves and
save data between a DataSet and Database.
• The DataAdapter is used fill method to fill a DataTable or DataSet.
• The DataAdapter can commit the changes to the database by its Update
method.
• DataAdapter provides four properties that represent database commands :
1. SelectCommand
2. InsertCommand
3. DeleteCommand
4. UpdateCommand
DataAdapter Class
• When the Data Adapter fills a DataSet, it will create the necessary tables
and columns for the returned data.
• There are two ways to initialize it.

string str = “Select * from emp”;


SqlConnection conn = new SqlConnection(“Data Source=”);
SqlCommand cmd = new SqlCommand(str , conn);
SqlDataAdapter da = new SqlDataAdapter (cmd);

string str = “Select * from emp”;


SqlConnection conn = new SqlConnection(“Data Source=”);
SqlCommand cmd = new SqlCommand(str , conn);
SqlDataAdapter da = new SqlDataAdapter (cmd);
da.SelectCommand = cmd;
DataSet Class
Data Set

Relations Table

Schema Column

Constraint

Row
DataSet Class
• ADO.NET caches data locally on the client and store that data into
DataSet.
• The dataset is a disconnected, in-memory representation of data. The
DataSet is populated DataAdapter’s Fill method.
• It’s not exact copy the Database. It can be considered as a local copy of the
some portions of the database.
• The DataSet contains a collection of one or more DataTable object made
up of rows and columns of data.
• Tables can be identified in DataSet using DataSet’s Tables property.
• It also contains primary key, foreign key, constraint and relation
information about the data in the DataTable objects.
• Whatever operations are made by the user it is stored temporary in
the DataSet, when the use of this DataSet is finished, changes can be
made back to the central database for updating.
• DataSet are also fully XML featured.
DataSet Class Example
using System.Data.SqlClient;
private void frmDb1_Load (object sender , EventArgs e)
{
SqlConnection conn = new SqlConnection (“Data Source = .\\SQLEXPRESS;
AttachDbFilename = D:\\DbGMIT.mdf; Integrated Security = True”);

SqlCommand cmd = new SqlCommand (“Select * from Emp” , conn);


SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill();
dataGridView1.DataSource = ds.Tables[0]; //DataTable
}
DataSet Class Example
private void btnsubmit_Click (object sender , EventArgs e)
{
String str = “Select * from emp where Salary <=” + txtSal.Text;
SqlConnection conn = new SqlConnection (“Data Source = .\\SQLEXPRESS;
AttachDbFilename = D:\\DbGMIT.mdf; Integrated Security = True”);

SqlCommand cmd = new SqlCommand (str , conn);


SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand = cmd;

DataSet ds = new DataSet();


da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0]; //DataTable
}
DataView Class
• DataView works with the DataTable.
• Every DataTable has a default DataView.
• With the help of DataView you can create different views of the data stored
in a DataTable, a capability that is often used in data-binding applications.
• Using a DataView, you can expose the data in a table with different sort
orders and filter data.
• A DataView provides you with a dynamic view of a single set of data to
which you can apply different sorting and filtering criteria, similar to the
view provided by any database software.
• DataView have important properties like sort and RowFilter.
• DataView does not affect the actual data store in the DataTable.
Example of DataView Properties
 Sort – There are 2 options available ascending / descending. By default
it support ASC.
 Syntax :
• DataViewName.Sort = “ColumnName”
• DataViewName.Sort = “ColumnName1 , ColumnName2”
• DataViewName.Sort = “ColumnName DESC”
• DataViewName.Sort = “ColumnName1 DESC , ColumnName2 ASC”
 Example :
• DataView dv = new DataView(ds.Tables(“Emp”))
• dv.Sort = “Salary”;
• dv.Sort = “Deptno , Empno”;
• dv.Sort = “Deptno DESC”;
• dv.Sort = “Deptno DESC , Ename ASC”;
Example of DataView Properties
 RowFilter – It works like where criteria
 Syntax :
• DataViewName.RowFilter = “ColumnName = ‘String1’ ”
• DataViewName.RowFilter = “ColumnName like ‘A%’ ”
• DataViewName.RowFilter = “ColumnName = No1”

 Example :
• DataView dv = new DataView(ds.Tables(“Emp”))
• dv.RowFilter = “FirstName = ‘Bhavin’ ”;
• dv.RowFilter = “FirstName like ‘R%’ ”;
• dv.RowFilter = “Empno = 5”;
Demo of Sorting using ComboBox and DataGridView

private void btnsubmit_Click (object sender , EventArgs e)


{
String str = “Select * from emp” ;
SqlConnection conn = new SqlConnection (“Data Source = .\\SQLEXPRESS;
AttachDbFilename = D:\\DbGMIT.mdf; Integrated Security = True”);
SqlCommand cmd = new SqlCommand (str , conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
DataView dv1 = new DataView (ds.Tables[0]);
dv1.Sort = cmbColName.Text;
dataGridView1.DataSource = dv1;
}
Demo of Filter using DataView
private void btnsubmit_Click (object sender , EventArgs e)
{
String str = “Select * from Product” ;
SqlConnection conn = new SqlConnection (“Data Source = .\\SQLEXPRESS;
AttachDbFilename = D:\\DbGMIT.mdf; Integrated Security = True”);
SqlCommand cmd = new SqlCommand (str , conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
DataView dv1 = new DataView (ds.Tables[0]);
dv1.RowFilter = “Price < ” + txtName.Text;
dataGridView1.DataSource = dv1;
}
Connected Mode
1 Create Connection

2 Create Command object and write down query

3 Create an object of Data Reader

4 Open Connection

5 Execute – ExecuteReader method of Command object

6 Access data through Read method of Data Reader

7 Close Connection
Connected Mode Example
using System;
public class connectedDemo
{
static void Main(String[] args)
{
SqlDataReader rdr;
SqlConnection con;
SqlCommand cmd;
try
{
String connectionstring = “Data Source =
.\\SQLEXPRESS; AttachDbFilename =
D:\\DbGMIT.mdf; Integrated Security = True”;
con = new SqlConnection (connectionstring);
con.Open();
Connected Mode Example
String CommandText = “SELECT FirstName,
LastName” + “ FROM Employees” ;
cmd.Connection = con;
rdr = cmd.ExecuteReader();
while( rdr.Read() )
{
Console.WriteLine(rdr[FirstName].ToString() + “ “
+ rdr[“LastName”].ToString() );
}
con.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
}
}
Disconnected Mode
1 Create Connection

2 Create Command object and write down query

3 Create an object of Data Adapter

4 Create an object of Data Set

5 Fill Data Set

6 Access data through DataTable, DataView, etc..

7 Close Connection
Disconnected Mode Example
using System;
public class DisconnectedDemo
{
static void Main(String[] args)
{
String connectionstring = “Data Source =
.\\SQLEXPRESS; AttachDbFilename =
D:\\DbGMIT.mdf; Integrated Security = True”;
//Create a connection String
SqlConnection con = new SqlConnection
(connectionstring);
// Open Connection
con.Open();
//Create a new command Object
SqlCommand cmd = new SqlCommand(“SELECT * FROM
Employees” , con);
Disconnected Mode Example
//Create adapter to Fill / Update dataset
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
//Create and fill Employee Table in dataset
Dataset ds = new Dataset();
adapter.Fill(ds , “Employees”);
//Display Data From Employee
Console.WriteLine(“Current DATA in EMPLOYEE table of
dataset”);
int count = 0;
Disconnected Mode Example
while(count <= ds.Tables[0].Rows.Count - 1)
{
Console.WriteLine(ds.Tables[0].Rows[count][0] +
“ “ + ds.Tables[0].Rows[count][1] + “ “ + ds.Tables[0].Rows[count][2] + “ “ +
ds.Tables[0].Rows[count][3]);
count = count + 1;
}
//ADD new row in DataSet
DataRow dr;
dr = ds.Tables[0].NewRow();
dr[“LastName”] = 2;
dr[“FirstName”] = “Demo”;
dr[“Title”] = “Demo”;
dr[“Address”] = “Demo”;
ds.Tables[0].Rows.Add(dr);
Disconnected Mode Example
//Use of CommandBuilder to set various command of adapter
SqlCommandBuilder builder;
builder = new SqlCommandBuilder (adapter);
adapter = builder.DataAdapter;

//Call update method of Adapter to store data in database


adapter.Update(ds , “Employee”);

//Close Connection
con.Close();
}
}
Data Binding
• Data Binding refers to the how we bind control to the database.
• There are three ways to bind data.

Manual Binding Simple Binding Complex Binding

1. Manual Binding :
• Manual binding means manual coding and refers steps connection,
command, data adapter, dataset.
Manual Binding - Example
using System.Data;
using System.Data.SqlClient;
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection(“ Data Source = C:\\
users\\Application3\\db1.mdf ”);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender , EventArgs e)
{
SqlCommand cmd = new SqlCommand (“Select * from
Dept ”);
Manual Binding - Example
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();

cmd.Connection = conn;
da.SelectCommand = cmd;
da.Fill(ds);
cmbDept.DataSource = ds.Tables[0];
cmbDept.DisplayMember = “DeptName”;
}
private void cmbDept_SelectedIndexChanged(object sender ,
EventArgs e)
{
dataGridView1.DataSource = “ ” ;
SqlCommand cmd2 = new SqlCommand();
Manual Binding - Example
cmd2.Connection = conn;
cmd2.CommandText = “Select EmpNo , EmpName ,
Salary from emp , dept where deptname = ‘” +
cmbDept.Text + “’ and Dept.DeptNo = Emp.DeptNo ” ;
SqlDataAdapter da2 = new SqlDataAdapter();
da2.SelectCommand = cmd2;
DataSet ds2 = new DataSet();
da2.Fill(ds2);
dataGridView1.DataSource = ds2.Tables;
}
}
Simple Binding
• In Simple data bind, data binds using Data binding property.
• It is easiest way to bind data with controls. We have to configure each and
every control differently.
• Simple Data binding requires less coding.

Rno 1

Name Rahul

Fees 12000

First Previous Next Last


Simple Binding - Example
private void btnFirst_Click(object sender , EventArgs e)
{
stuBindingSource.MoveFirst();
}
private void btnPrevious_Click(object sender , EventArgs e)
{
stuBindingSource.MovePrevious();
}
private void btnNext_Click(object sender , EventArgs e)
{
stuBindingSource.MoveNext();
}
private void btnLast_Click(object sender , EventArgs e)
{
stuBindingSource.MoveLast();
}
Complex Binding
• The difference between simple and complex data binding that at a time we
can view single record at a time while in complex data binding we can
view multiple records at a time.
• Complex Data Binding involves the following properties :
Property Name Description
DataSource Indicates the source of the DataGridView, usually
DataSet.
DataMember Indicates sub list of the DataSource to show in the
DataGridView controls. Means Table Name – Stu
DisplayMember Indicates the column(field) we want a control to
display for example Rno, Sname, Marks etc..
ValueMember Indicates the column we want a control to return
for example for select Sname but in background
Rno
Complex Binding - Example
using System.Data.SqlClient;
private void frmComplex_Load(object sender , EventArgs e)
{
SqlConnection conn = new SqlConnection (“Data Source = C:\\
prj\\db1.mdf ”);

SqlCommand cmd = new SqlCommand(“Select * from Dept” ,


conn);

SqlDataAdapter da = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();


da.Fill(ds);

dataGridView1.DataSource = ds.Tables;
}
Example
• ADO.NET main program, 4 buttons for Navigations, 4 buttons for Add-
Update-Delete-Cancel.

RollNo 1

Name Rahul

DOB 01/01/2000

Gender Male Female

Std

<< < > >>

Add Save Delete Cancel


Example
using System.Data.SqlClient;
namespace slnDemo
{
public partial class frmAdoM : Form
{
public frmAdoM()
{
InitializeComponent();
}
// Global Variables
SqlConnection conn;
SqlCommand cmd;
SqlDataAdapter da;
DataSet ds;
int pos = 0;
bool boolDbChange = false;
bool boolAddmode = false;
Example
private void frmAdoM_Load(object sender , EventArgs e)
{
conn = new SqlConnection (“Data Source = .\\SQLEXPRESS;
AttachDbFilename = D:\\DbGMIT.mdf; Integrated Security = True”);
cmd = new SqlCommand(“Select * from Stu” , conn);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
showRec();
}
private void btnFirst_Click(object sender , EventArgs e)
{
pos = 0;
showRec();
}
Example
private void btnPre_Click(object sender , EventArgs e)
{
if (pos > 0)
{
pos = pos – 1;
showRec();
}
}
private void btnNext_Click(object sender , EventArgs e)
{
if (pos < ds.Tables[0].Rows.Count - 1)
{
pos = pos + 1;
showRec();
}
}
Example
private void btnLast_Click(object sender , EventArgs e)
{
pos = ds.Tables[0].Rows.Count – 1;
showRec();
}
private void btnAdd_Click(object sender , EventArgs e)
{
boolAddmode = true;
txtName.Clear();
txtStd.Clear();
lblSno.Text = GetNewID().ToString();
}
Example
private void btnSave_Click(object sender , EventArgs e)
{
int gen;
SqlCommand tmpCmd = new SqlCommand();
string strQry = “”;
if (optMale.Checked == true)
{
gen = 1;
}
else
{
gen = 0;
}
tmpCmd.Connection = conn;
Example
if (boolAddmode == true)
{
strQry = “insert into Stu value(“ + lblSno.Text + “,” + txtName.Text
+ “,” + dtPicker.Text + “,” + gen + “,” + txtStd.Text + “)”;
}
else
{
strQry = “Update Stu set Sname = ‘“ + txtName.Text + ”’ , DOB = ‘“
+ dtPicker.Text + ”’ , Gender = “ + gen + “ , Std = “ + txtStd.Text + “ where
Sno = “ + lblSno.Text ;
}
tmpCmd.CommandText = strQty;
conn.Open();
tmpCmd.ExecuteNonQuery();
conn.Close();
Example
if (boolAddmode == true)
{
pos = ds.Tables[0].Rows.Count;
MessageBox.show(“Record Added”);
}
else
{
MessageBox.show(“Record Updated”);
}
boolDbChange = true ;
boolAddmode = false ;
}
Example
private void btnDel_Click(object sender , EventArgs e)
{
SqlCommand tmpCmd = new SqlCommand();
string strQry = “Delete from Stu where Sno = ” + lblSno.Text;
tmpCmd.Connection = conn;
tmpCmd.CommandText = strQry;
conn.Open();
tmpCmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show(“Record Deleted”);
boolDbChange = true;
if (pos == 0)
{
pos = pos + 1;
}
Example
else
{
pos = pos - 1;
}
showRec();
}
private void btnCancel_Click(object sender , EventArgs e)
{
boolAddmode = false;
showRec();
}
Example
void showRec() // Method for display to the relevant control
{
if (boolDbChange = = true)
{
ds = new DataSet();
da.Fill(ds);
boolDbChange = false;
}
lblSno.Text = ds.Tables[0].Rows[pos][“SNo”].ToString();
lblName.Text = ds.Tables[0].Rows[pos][“SName”].ToString();
dtPicker.Text = ds.Tables[0].Rows[pos][“DOB”].ToString();
bool gen;
gen = Convert.ToBoolean(ds.Tables[0].Rows[pos][“Gender]”);
Example
if (gen = = true)
{
optMale.Checked = true;
}
else
{
optFemale.Checked = true;
}
txtStd.Text = ds.Table[0].Rows[pos][“Std”].ToString();
}
Example
int GetNewID() //Method which returns new id
{
int id = 0;
SqlCommand tmpCmd = new SqlCommand();
tmpCmd.Connection = conn;
tmpCmd.CommandText = “Select max(SNo) from Stu” ;
conn.Open();
id = Convert.ToInt16( tmpCmd.ExecuteScalar() );
conn.Close();
return id + 1;
}
} // End of Class
} // End of Namespace
Questions
1. What do you mean by managed provider? How managed provides are
supported in ADO.NET. (Summer 2016 , Winter 2015)
2. Write ADO.NET program in code behind language C# which shows
records from student_details (S_No , S_Name , S_Address) on console
application. (Summer 2016)
S_No S_Name S_Address
1 Aryaveer Ahmedabad
2 Jeetraj Baroda
3 Dhruvin Surat

3. Draw and explain ADO.NET architecture with its new features. (Summer
2016 , Winter 2015).
4. What was ADO Technology? How it differs from ADO.NET Technology?
Explain. (Summer 2016)
Questions
5. Explain usage of following ADO.NET objects with their methods.
(Summer - 2016)
• SqlDataAdapter
• SqlCommand object
• Dataset
6. What is SqlDataReader? Explain it with relevant example. (Summer -
2016)
7. List and Explain common namespace used for ADO.NET. Also list most
common classes in those namespace. (Summer - 2015)
8. Write a short note : ADO.NET (Winter - 2014)
9. Explain data sets and data binding related to ADO.NET. (Winter - 2014)
10. List and Explain important classes of ADO.NET. (Summer – 2014 ,
Winter - 2013)
11. What do you mean by managed provider? How managed provides are
supported in ADO.NET. (Winter - 2016)
Questions
12. Explain following features of ADO.NET ? (Winter - 2013)
• Managed provider
• Disconnected data access
13. Write a ADO.NET program which shows record from student_master
(name , email , city , phone) on console. (Winter - 2013).
14. Write a ADO.NET program which shows record from student_master
(name , email , city , phone) on DataGridView and GridView. (Winter -
2016)
15. Draw and explain ADO.NET architecture in detail. (Summer - 2017)
16. Explain usage of following ADO.NET objects with their methods.
(Summer – 2017).
• SqlDataAdapter
• SqlCommand object
• Dataset
17. Write a C# code to bind data from given table to ComboBox Control
using DataAdapter. Table : Student (EnNo , Name). (Summer - 2017)
You
a n k
T h

You might also like