0% found this document useful (0 votes)
51 views67 pages

Notesss

Uploaded by

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

Notesss

Uploaded by

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

DO

AND.NET
INTRODUCTION

ADO.NET is a set of classes that allows you to connect and work with data sources

like databases, excel file, access file, xml file, mysql, sql or notepad. To connect your

application with different sources of database you need to know the right Data

Provider. There are several Data Providers in ADO.NET that connects with different

types of sources. A list of ADO.NET Data Providers is listed below:

.NET DATA PROVIDERS

We know that ADO.NET allows us to interact with different types of data sources

and different types of databases. However, there isn’t a single set of classes that

allow you to accomplish this universally. Since different data sources expose

different protocols, we need a way to communicate with the right data source using

the right protocol Some older data sources use the ODBC protocol, many newer data

sources use the OleDb protocol, and there are more data sources every day that

allow you to communicate with them directly through .NET ADO.NET class libraries.

ADO.NET provides a relatively common way to interact with data sources but comes

in different sets of libraries for each way you can talk to a data source. These

libraries are called Data Providers and are usually named for the protocol or data

source type they allow you to interact with. The table below lists some well-known

data providers, the API prefix they use, and the type of data source they allow you

to interact with.

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 1


Provider Name API prefix Data Source Description

ODBC Data Data Sources with an ODBC interface. Normally


Odbc
Provider older databases.

OleDb Data Data Sources that expose an OleDb interface, i.e.


OleDb
Provider Access or Excel.

Oracle Data
Oracle For Oracle Databases.
Provider

SQL Data
SQL For interacting with Microsoft SQL Server.
Provider

Borland Data Generic access to many databases such as


Bdp
Provider Interbase, SQL Server, IBM DB2, and Oracle.

CORE COMPONENTS OF .NET DATA PROVIDERS

There are 4 Core Components of .Net Data Providers that is used to connect, access

and retrieve data from the database.

1. Connection – This component is used for connecting to the database. The base

class is DbConnection.

2. Command – This component executes SQL query against the data source. The base

class is DbCommand.

3. DataReader – It reads data from data source. It accesses data read-only and

forward-only. The base class is DbDataReader.

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 2


4. DataAdapter – It invokes dataset and resolves updates with the data source. The

base class is DbDataAdapter.

ADO.NET Objects

ADO.NET includes many objects you can use to work with data. This section

introduces some of the primary objects you will use. The objects below are the ones

you must know. Learning about them will give you an idea of the types of things you

can do with data when using ADO.NET.

The SqlConnection Object

To interact with a database, you must have a connection to it. The connection helps

identify the database server, the database name, username, password, and other

parameters that are required for connecting to the database. A connection object

is used by command objects so they will know which database to execute the

command on.

The SqlCommand Object

The process of interacting with a database means that you must specify the actions

you want to occur. This is done with a command object. You use a command object to

send SQL statements to the database. A command object uses a connection object

to figure out which database to communicate with.

The SqlDataReader Object

Many data operations require that you only get a stream of data for reading. The

data reader object allows you to obtain the results of a SELECT statement from a

command object. For performance reasons, the data returned from a data reader is

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 3


a fast forward-only stream of data. This means that you can only pull the data from

the stream in a sequential manner. This is good for speed, but if you need to

manipulate data, then a DataSet is a better object to work with.

The DataSet Object

DataSet objects are in-memory representations of data. They contain multiple

Datatable objects, which contain columns and rows, just like normal database tables.

You can even define relations between tables to create parent-child relationships.

The DataSet is specifically designed to help manage data in memory and to support

disconnected operations on data when such a scenario make sense. The DataSet is

an object that is used by all of the Data Providers, which is why it does not have a

Data Provider specific prefix.

The SqlDataAdapter Object

Sometimes the data you work with is primarily read-only and you rarely need to make

changes to the underlying data source. Some situations also call for caching data in

memory to minimize the number of database calls for data that does not change. The

data adapter makes it easy for you to accomplish these things by helping to manage

data in a disconnected mode. The data adapter fills a DataSet object when reading

the data and writes in a single batch when persisting changes back to the database.

A data adapter contains a reference to the connection object and opens and closes

the connection automatically when reading from or writing to the database.

Additionally, the data adapter contains command object references for SELECT,

INSERT, UPDATE, and DELETE operations on the data. You will have a data adapter

defined for each table in a DataSet and it will take care of all communication with

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 4


the database for you. All you need to do is tell the data adapter when to load from

or write to the database.

Step 1: Create a database

1. Open Visual Studio.

2. Go to Server Explorer. If Server Explorer is not opened go to View Server

Explorer.

3. Right click on Data Connections and select Create New SQL Server Database.

4. Fill details like this.

a. Server Name: .\SQLEXPRESS

b. Select Windows Authentication

c. Database Name: TestDB

d. Click OK.

Step 2: Create Table

1. Now, Expand your database Right click on Tables Add New Table.

2. Create a new table like this.

Query:

CREATE TABLE [dbo].[Student] (

1. [Id] INT NOT NULL,

2. [Name] NVARCHAR (50) NULL,

3. [Subject] NVARCHAR (50) NULL,

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 5


4. PRIMARY KEY CLUSTERED ([Id] ASC)

5. );

3. After finishing table click on Update button that is the upper right corner of

design pane.

4. Right click on Student Table and select Show Table Data. Now, fill some demo

data in it like this.

Step 3: Get Connection String

1. Now, your database and tables are ready. You can find your connection string in

properties of the database.

a. Right Click on Database Properties. Now, you have a database with a table and a

connection string. The next step is to connect to the database and retrieve the

records using ADO.Net Commands.

RETRIEVE RECORD IN CONSOLE APPLICATION

Start New Console Application.

1. Go to File > New > Project. Create a new console application, FirstProgram and

click OK.

2. Paste the following code in the program window and press ctrl + F5

using System;

1. using System.Data.SqlClient;

2.

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 6


3. namespace FirstProgram

4. {

5. class Program

6. {

7. static void Main(string[] args)

8. {

9. string ConString = @"Data Source=.\SQLEXPRESS;Initial

Catalog=TestDB;Integrated Security=True";

10. SqlConnection con = new SqlConnection(ConString);

11. string querystring = "Select * from Student";

12. con.Open();

13. SqlCommand cmd = new SqlCommand(querystring, con);

14. SqlDataReader reader = cmd.ExecuteReader();

15. while (reader.Read())

16. {

17. Console.WriteLine(reader[0].ToString() + " " + reader[1].ToString()

+ " " + reader[2].ToString());

18. }

19. }

20. }

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 7


21. }

Output

1 Jack C#

2 Mathew Java

3 Steven C++

RETRIEVE RECORDS IN WINDOWS APPLICATION

Create New Project

1. Go to File New Project. Select Windows Form Application (C#), give project

name FirstForm and click OK.

2. Drag and Drop a Button and a Label Control to Form. You can find these controls

on Tool Box. If Tool Box is not available to open it from View Tool Box

3. Double Click on the Button control. It will open button_click event in code windows.

Now paste the following code.

1. using System;

2. using System.Windows.Forms;

3. using System.Data.SqlClient;

4.

5. namespace FirstForm

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 8


6. {

7. public partial class Form1 : Form

8. {

9. public Form1()

10. {

11. InitializeComponent();

12. }

13.

14. private void button1_Click(object sender, EventArgs e)

15. {

16. string ConString = @"Data Source=.\SQLEXPRESS;Initial

Catalog=TestDB;User ID=sa;Password=System123;Pooling=False";

17. SqlConnection con = new SqlConnection(ConString);

18. string querystring = "Select * from Student";

19. con.Open();

20. SqlCommand cmd = new SqlCommand(querystring, con);

21. SqlDataReader reader = cmd.ExecuteReader();

22. while (reader.Read())

23. {

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 9


24. label1.Text = reader[0].ToString() + " " + reader[1].ToString() + " "

+ reader[2].ToString();

25. }

26. }

27. }

28. }

WORKING WITH DB

Connection Object - Connecting To Database Using C# ADO.Net

In this chapter you will learn:

1. What is Connection Object in ADO.Net?

2. What is Connection String?

3. How to Store Connection String in web.config and App.config file?

4. How to connect to Database using C# ADO.Net

WHAT IS CONNECTION OBJECT IN ADO.NET?

Connection Object is used for connecting your application to data source or

database. It carries required authentic information like username and password in

the connection string and opens a connection. You need to different type of

connection object for different type of data providers. For example:

OLE DB – OleDbConnection

SQL Server – SqlConnection

ODBC – OdbcConnection

Oracle – OracleConnection

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 10


WHAT IS CONNECTION STRING?

Connection String combines all the required authentic information that is used for

connecting to a Data Source, like Server Name, Database Name, User Name,

Password etc. It is just a single line string that is used by connection object to

connect to the database. A connection string looks like this.

Data Source=.\SQLEXPRESS;Initial Catalog=TestDB;Integrated Security=True

or,

Data Source=.\SQLEXPRESS;Initial Catalog=TestDB;User

ID=sa;Password=System123;Pooling=False

HOW TO STORE CONNECTION STRING IN WEB.CONFIG FILE?

In order to connect with Database, it is mandatory to keep connection string in a

safe and centralized location. It is not recommended to writing connection string in

each and every connection. You can store the connection string

in Web.config file, app.config file or into a class file.

WEB.CONFIG FILE – ADD AND RETRIEVE CONNECTION STRING

If you are developing ASP.Net Project or ASP Web Project then you can store the

connection string in Web.config file.

1. Open Web.config file from solution Explorer

2. Paste following code Just Before </Configuration>

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 11


1. <connectionStrings>

2. <add name="StudentConn" connectionString="Data

Source=.\SQLEXPRESS;Initial Catalog=StudentDB;Integrated

Security=True;Pooling=False"/>

3. </connectionStrings>

Access Connection String from web.config

You can access this connection string in ASP.NET MVC, like this

1. using System.Configuration;

2.

3. namespace ConnectionString_Example.Controllers

4. {

5. public class conString

6. {

7. public string getConString()

8.

9. {

10. string constring =

ConfigurationManager.ConnectionStrings["studentconn"].ToString();

11. return constring;

12. }

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 12


13. }

14. }

APP.CONFIG FILE – ADD AND RETRIEVE CONNECTION STRING

If you are working on the windows form, you can save connection string

in App.config file.

Add Connection String into app.config

1. <connectionStrings>

2. <add name="StudentConn" connectionString="Data

Source=.\SQLEXPRESS;Initial Catalog=TestDB;User

ID=sa;Password=System123;Pooling=False"/>

3. </connectionStrings>

Retrieve Connection String from app.config

1. using System;

2. using System.Windows.Forms;

3. using System.Data.SqlClient;

4. using System.Configuration;

5.

6. namespace FirstForm

7. {

8. public partial class Form1 : Form

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 13


9. {

10. public Form1()

11. {

12. InitializeComponent();

13. }

14.

15. private void button1_Click(object sender, EventArgs e)

16. {

17. var ConString =

ConfigurationManager.ConnectionStrings["StudentConn"].ConnectionString;

18. SqlConnection con = new SqlConnection(ConString);

19. con.Open();

20. }

21. }

22. }

If ConfigurationManager Object does not appear or giving reference error, then you

should add reference to ConfigurationManager Object like this.

1. Right Click on References in Solution Explorer and select Add Reference…

2. Reference Manager window will appear. Here, Choose Framework in left panel and

then find and check System.Configuration in Middle Panel.

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 14


3. Click OK to add Reference.

CONNECT TO DATASOURCE

There are 5 steps to connecting database.

1. Add Namespace: using System.Data.SqlClient;

2. Create Connection Object and Pass Connection String as Parameter.

3. 3. Open Connection

4. Execute SQL Query

5. 5. Close the Connection.

Example

1. SqlConnection con = new SqlConnection("Data Source=.\SQLEXPRESS;Initial

Catalog=TestDB;User ID=sa;Password=System123;Pooling=False"; );

2. con.Open();

3. // Update, Insert Delete Job in Table

4. con.Close();

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 15


ADO.NET CONNECTIONS

The first thing you will need to do when interacting with a database is to create a

connection. The connection tells the rest of the ADO.NET code which database it is

talking to. It manages all of the low-level logic associated with the specific database

protocols. This makes it easy for you because the most work you will have to do in

code instantiates the connection object, open the connection, and then close the

connection when you are done. Because of the way that other classes in ADO.NET

are built, sometimes you don’t even have to do that much work.

Although working with connections is very easy in ADO.NET, you need to understand

connections in order to make the right decisions when coding your data access

routines. Understand that a connection is a valuable resource. Sure, if you have a

stand-alone client application that works on a single database one machine, you

probably don’t care about this. However, think about an enterprise application where

hundreds of users throughout a company are accessing the same database. Each

connection represents overhead and there can only be a finite amount of them. To

look at a more extreme case, consider a Web site that is being hit with hundreds of

thousands of hits a day Applications that grab connections and don’t let them go can

have serious negative impacts on performance and scalability.

Creating a SqlConnection Object

A SqlConnection is an object, just like any other C# object. Most of the time, you

just declare and instantiate the SqlConnection all at the same time, as shown below:

SqlConnection conn = new SqlConnection(

"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 16


The SqlConnection object instantiated above uses a constructor with a single

argument of type string. This argument is called a connection string. The table below

describes common parts of a connection string.

Table. ADO.NET Connection Strings contain certain key/value pairs for

specifying how to make a database connection. They include the location, name

of the database, and security credentials.

Connection String
Description
Parameter Name

Identifies the server. Could be local machine,


Data Source
machine domain name, or IP Address.

Initial Catalog Database name.

Set to SSPI to make the connection with user’s


Integrated Security
Windows login

User ID Name of user configured in SQL Server.

Password Password matching SQL Server User ID.

Integrated Security is secure when you are on a single machine doing development.

However, you will often want to specify security based on a SQL Server User ID

with permissions set specifically for the application you are using. The following

shows a connection string, using the User ID and Password parameters:

SqlConnection conn = new SqlConnection(

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 17


"Data Source=DatabaseServer;Initial Catalog=Northwind;User

ID=YourUserID;Password=YourPassword");

Notice how the Data Source is set to DatabaseServer to indicate that you can

identify a database located on a different machine, over a LAN, or over the Internet.

Additionally, User ID and Password replace the Integrated Security parameter.

Using a SqlConnection

The purpose of creating a SqlConnection object is so you can enable other ADO.NET

code to work with a database. Other ADO.NET objects, such as a SqlCommand and

a SqlDataAdapter take a connection object as a parameter. The sequence of

operations occurring in the lifetime of a SqlConnection are as follows:

1. Instantiate the SqlConnection.

2. Open the connection.

3. Pass the connection to other ADO.NET objects.

4. Perform database operations with the other ADO.NET objects.

5. Close the connection.

We’ve already seen how to instantiate a SqlConnection. The rest of the steps,

opening, passing, using, and closing are shown below.

using System;

using System.Data;

using System.Data.SqlClient;

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 18


/// <summary>

/// Demonstrates how to work with SqlConnection objects

/// </summary>

class SqlConnectionDemo

static void Main()

// 1. Instantiate the connection

SqlConnection conn = new SqlConnection(

"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");

SqlDataReader rdr = null;

try

// 2. Open the connection

conn.Open();

// 3. Pass the connection to a command object

SqlCommand cmd = new SqlCommand("select * from Customers", conn);

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 19


//

// 4. Use the connection

//

// get query results

rdr = cmd.ExecuteReader();

// print the CustomerID of each record

while (rdr.Read())

Console.WriteLine(rdr[0]);

finally

// close the reader

if (rdr != null)

rdr.Close();

// 5. Close the connection

if (conn != null)

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 20


{

conn.Close();

As shown above, you open a connection by calling the Open() method of

the SqlConnection instance, conn. Any operations on a connection that was not yet

opened will generate an exception. So, you must open the connection before using it.

Before using a SqlCommand, you must let the ADO.NET code know which connection

it needs. We set the second parameter to the SqlCommand object with

the SqlConnection object, conn. Any operations performed with the SqlCommand will

use that connection.

The code that uses the connection is a SqlCommand object, which performs a query

on the Customers table. The result set is returned as a SqlDataReader and

the while loop reads the first column from each row of the result set, which is the

CustomerID column. Right now, it is important for you to understand that these

objects are using the SqlConnection object so they know what database to interact

with.

When you are done using the connection object, you must close it. Failure to do so

could have serious consequences in the performance and scalability of your

application. There are a couple points to be made about how we closed the connection

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 21


above: the Close()method is called in a finally block and we ensure that the

connection is not null before closing it.

Notice that we wrapped the ADO.NET code in a try/finally block. The finally blocks

help guarantee that a certain piece of code will be executed, regardless of whether

or not an exception is generated. Since connections are scarce system resources,

you will want to make sure they are closed in finally blocks.

Another precaution you should take when closing connections is to make sure the

connection object is not null. If something goes wrong when instantiating the

connection, it will be null and you want to make sure you don’t try to close an invalid

connection, which would generate an exception.

You have seen how to use a SqlConnection object with a SqlDataReader, which

required explicitly closing the connection. However, when using a disconnected data

model, you don’t have to open and close the connection yourself.

INSERT RECORDS USING SIMPLE AND PARAMETERIZED QUERY – C# SQL

The keyword INSERT INTO is used for inserting records in a table. There are 2

ways to insert records in a table.

1. Insert using Simple Query

2. Insert using Parameterized Query

Direct Insert Record in a Table

This is the easiest way to insert records into a table but I strongly avoid it because

it is less secure than parameterized query.

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 22


Syntax

1. INSERT INTO table_name (column1, column2, column3, ...)

2. VALUES (value1, value2, value3, ...);

or,

1. INSERT INTO table_name

2. VALUES (value1, value2, value3, ...);

Programming Example

1. using System;

2. using System.Data.SqlClient;

3.

4. namespace InsertRecords

5. {

6. class Program

7. {

8. static void Main(string[] args)

9. {

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 23


10. SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Ini

tial Catalog=ComputerShop;Integrated Security=True");

11. string query = "INSERT INTO Products (Name,Price,Date) VALUES('LED S

creen','$120','27 January 2017')";

12. SqlCommand cmd = new SqlCommand(query, con);

13. try

14. {

15. con.Open();

16. cmd.ExecuteNonQuery();

17. Console.WriteLine("Records Inserted Successfully");

18. }

19. catch (SqlException e)

20. {

21. Console.WriteLine("Error Generated. Details: " + e.ToString());

22. }

23. finally

24. {

25. con.Close();

26. Console.ReadKey();

27. }

28. }

29. }

30. }

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 24


Output:

Records Inserted Successfully

PARAMETERIZED QUERY

We always prefer to use Parameterized Query over simple SQL Query because it

prevents SQL Injection Attacks. Here is programming example in which you can learn

how to use Parameterized query in C# SQL.

Programming Example

1. using System;

2. using System.Data.SqlClient;

3.

4. namespace InsertRecords

5. {

6. class Program

7. {

8. static void Main(string[] args)

9. {

10. SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Ini

tial Catalog=ComputerShop;Integrated Security=True");

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 25


11. //Replaced Parameters with Value

12. string query = "INSERT INTO Products (Name, Price, Date) VALUES(@Na

me, @Price, @Date)";

13. SqlCommand cmd = new SqlCommand(query, con);

14.

15. //Pass values to Parameters

16. cmd.Parameters.AddWithValue("@Name", "USB Keyboard");

17. cmd.Parameters.AddWithValue("@Price", "$20");

18. cmd.Parameters.AddWithValue("@Date", "25 May 2017");

19.

20. try

21. {

22. con.Open();

23. cmd.ExecuteNonQuery();

24. Console.WriteLine("Records Inserted Successfully");

25. }

26. catch (SqlException e)

27. {

28. Console.WriteLine("Error Generated. Details: " + e.ToString());

29. }

30. finally

31. {

32. con.Close();

33. Console.ReadKey();

34. }

35. }

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 26


36. }

37. }

Output

Records Inserted Successfully

WHAT IS STORE PROCEDURE?

A Store Procedure is a Pre Compiled SQL Queries that is saved into server. The

Benefit of Store Procedure is you don't need to write same SQL Queries again and

again. Store Procedure get compiled once and can be used forever. However, it is

easy to create store procedure in SQL Server Management Studio but here I will

explain how you can create and execute Store Procedure right from your program.

CREATE STORE PROCEDURE USING C# ADO.NET

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 27


Here, I am going to create Store Procedure for saving and retrieving records

from ComputerShop Database.

Create Store Procedure SQL Queries

1. CREATE PROCEDURE Insert_Record_Procedure

2. (

3. @Name VARCHAR(50),

4. @Price VARCHAR(50),

5. @Date DATETIME

6. )

7. AS

8. INSERT INTO Products(Name,Price,Date) Values(@Name,@Price,@Date

You can create this store procedure in Server Explorer or SQL Server Management

Studio. Here, I have created this store procedure using C#.

Programming Example of Creating Store Procedure

1. using System;

2. using System.Data.SqlClient;

3.

4. namespace Create_Store_Procedure

5. {

6. class Program

7. {

8. static void Main(string[] args)

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 28


9. {

10. SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Ini

tial Catalog=ComputerShop;Integrated Security=True");

11. string query =

12. @"

13. CREATE PROCEDURE Insert_Record_Procedure

14. (

15. @Name VARCHAR(50),

16. @Price VARCHAR(50),

17. @Date DATETIME

18. )

19. AS

20. INSERT INTO Products(Name,Price,Date) Values(@Name,@Price,@Date

21. ";

22.

23. SqlCommand cmd = new SqlCommand(query, con);

24. try

25. {

26. con.Open();

27. cmd.ExecuteNonQuery();

28. Console.WriteLine("Store Procedure Created Successfully");

29. }

30. catch (SqlException e)

31. {

32. Console.WriteLine("Error Generated. Details: " + e.ToString());

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 29


33. }

34. finally

35. {

36. con.Close();

37. Console.ReadKey();

38. }

39. }

40. }

41. }

INSERT RECORDS TO TABLE USING STORE PROCEDURE

1. using System;

2. using System.Data.SqlClient;

3. using System.Data;

4.

5. namespace Create_Store_Procedure

6. {

7. class Program

8. {

9. static void Main(string[] args)

10. {

11. SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Ini

tial Catalog=ComputerShop;Integrated Security=True");

12. SqlCommand cmd = new SqlCommand("Insert_Record_Procedure", con);

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 30


13. try

14. {

15. con.Open();

16. cmd.CommandType = CommandType.StoredProcedure;

17. cmd.Parameters.Add(new SqlParameter("@Name", "SSD DRIVE"));

18. cmd.Parameters.Add(new SqlParameter("@Price", "$300"));

19. cmd.Parameters.Add(new SqlParameter("@Date" , "25 August 14"));

20. int i = cmd.ExecuteNonQuery();

21. if(i>0)

22. {

23. Console.WriteLine("Records Inserted Successfully.");

24. }

25.

26. }

27. catch (SqlException e)

28. {

29. Console.WriteLine("Error Generated. Details: " + e.ToString());

30. }

31. finally

32. {

33. con.Close();

34. Console.ReadKey();

35. }

36. }

37. }

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 31


38. }

Output:

Records Inserted Successfully.

RETRIEVE RECORDS USING STORE PROCEDURE C#

Here, you need to create one more Store Procedure to retrieve records from

database table.

1. CREATE PROCEDURE Retrieve_Record_Proc

2. (

3. @Name VARCHAR(50)

4. )

5. AS

6. SELECT * FROM Products where Name=@Name

Programming Example

1. using System;

2. using System.Data.SqlClient;

3. using System.Data;

4.

5. namespace Create_Store_Procedure

6. {

7. class Program

8. {

9. static void Main(string[] args)

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 32


10. {

11. SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Ini

tial Catalog=ComputerShop;Integrated Security=True");

12. try

13. {

14. con.Open();

15. SqlCommand cmd = new SqlCommand("Retrieve_Record_Proc", con);

16. cmd.CommandType = CommandType.StoredProcedure;

17. cmd.Parameters.Add(new SqlParameter("@Name", "HardDisk"));

18. SqlDataReader dr = cmd.ExecuteReader();

19. while(dr.Read())

20. {

21. Console.WriteLine("Product Name : " + dr[1].ToString());

22. Console.WriteLine("Price : " + dr[2].ToString());

23. Console.WriteLine("Date : " + dr[3].ToString());

24. }

25.

26. }

27. catch (SqlException e)

28. {

29. Console.WriteLine("Error Generated. Details: " + e.ToString());

30. }

31. finally

32. {

33. con.Close();

34. Console.ReadKey();

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 33


35. }

36. }

37. }

38. }

Output

Product Name : HardDisk Price : $200 Date : 24-01-2017 AM 12:00:00

DATAREADER ADO.NET

The DataReader object in C# ADO.NET allows you to retrieve data from database

in read-only and forward-only mode. It means you can only read and display data but

can’t update or delete data. If you want to make modification in retrieved data you

need to use DataAdapter instead of DataReader.

A SqlDataReader is a type that is good for reading data in the most efficient manner

possible. You can *not* use it for writing data. SqlDataReaders are often described

as fast-forward firehose-like streams of data.

You can read from SqlDataReader objects in a forward-only sequential manner. Once

you’ve read some data, you must save it because you will not be able to go back and

read it again.

The forward only design of the SqlDataReader is what enables it to be fast. It

doesn’t have the overhead associated with traversing the data or writing it back to

the data source. Therefore, if your only requirement for a group of data is for

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 34


reading one time and you want the fastest method possible, the SqlDataReader is

the best choice. Also, if the amount of data you need to read is larger than what you

would prefer to hold in memory beyond a single call, then the streaming behavior of

the SqlDataReader would be a good choice.

WHY AND WHEN TO USE DATAREADER?

When you want to only display information or search result, you can use DataReader.

There are various advantages of using DataReader like:

1. The retrieved data is stored in the network buffer in the client and then the client

can read data using Read method. As data gets stored in the client network buffer

it increases application performance significantly.

2. By default DataReader stores only one row at a time in memory. It reduces system

overhead.

METHODS AND PROPERTIES OF DATAREADER

Properties

PROPERTY DESCRIPTION

Depth Indicates the depth of nesting for row

FieldCount Returns number of columns in a row

IsClosed Indicates whether a data reader is closed

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 35


Item Gets the value of a column in native format

RecordsAffected Number of row affected after a transaction

Methods

METHOD DESCRIPTION

Close Closes a DataRaeder object.

Read Reads next record in the data reader.

NextResult Advances the data reader to the next result

during batch transactions.

Getxxx Creating a SqlDataReader Object

Getting an instance of a SqlDataReader is a little different than the way you

instantiate other ADO.NET objects. You must allExecuteReader on a command

object, like this:

SqlDataReader rdr = cmd.ExecuteReader();

The ExecuteReader method of the SqlCommand object, cmd, returns a

SqlDataReader instance. Creating a SqlDataReader with the new operator doesn’t do

anything for you. As you learned in previous lessons, the SqlCommand object

references the connection and the SQL statement necessary for the SqlDataReader

to obtain data.

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 36


Reading Data

previous lessons contained code that used a SqlDataReader, but the discussion was

delayed so we could focus on the specific subject of that particular lesson. This

lesson builds from what you’ve seen and explains how to use the SqlDataReader.

As explained earlier, the SqlDataReader returns data via a sequential stream. To

read this data, you must pull data from a table row-by-row Once a row has been read,

the previous row is no longer available. To read that row again, you would have to

create a new instance of the SqlDataReader and read through the data stream again.

The typical method of reading from the data stream returned by the SqlDataReader

is to iterate through each row with a while loop. The following code shows how to

accomplish this:

while (rdr.Read())

// get the results of each column

string contact = (string)rdr["ContactName"];

string company = (string)rdr["CompanyName"];

string city = (string)rdr["City"];

// print out the results

Console.Write("{0,-25}", contact);

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 37


Console.Write("{0,-20}", city);

Console.Write("{0,-25}", company);

Console.WriteLine();

Notice the call to Read on the SqlDataReader, rdr, in the while loop condition in the

code above. The return value of Read is type bool and returns true as long as there

are more records to read. After the last record in the data stream has been

read, Read returns false.

In previous lessons, we extracted the first column from the row by using the

SqlDataReader indexer, i.e. rdr[0]. You can extract each column of the row with a

numeric indexer like this, but it isn’t very readable. The example above uses a string

indexer, where the string is the column name from the SQL query (the table column

name if you used an asterisk, *. String indexers are much more readable, making the

code easier to maintain.

Regardless of the type of the indexer parameter, a SqlDataReader indexer will

return type object. This is why the example above casts results to a string. Once

the values are extracted, you can do whatever you want with them, such as printing

them to output with Console type methods.

Always remember to close your SqlDataReader, just like you need to close the

SqlConnection. Wrap the data access code in a try block and put the close

operation in the final block, like this:

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 38


try

// data access code

finally

// 3. close the reader

if (rdr != null)

rdr.Close();

// close the connection too

The code above checks the SqlDataReader to make sure it isn’t null. After the

code knows that a good instance of the SqlDataReader exists, it can close it.

Listing 1 shows the code for the previous sections in its entirety.

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 39


Using the SqlDataReader

using System;

using System.Data;

using System.Data.SqlClient;

namespace Lesson04

class ReaderDemo

static void Main()

ReaderDemo rd = new ReaderDemo();

rd.SimpleRead();

public void SimpleRead()

// declare the SqlDataReader, which is used in

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 40


// both the try block and the finally block

SqlDataReader rdr = null;

// create a connection object

SqlConnection conn = new SqlConnection(

"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");

// create a command object

SqlCommand cmd = new SqlCommand(

"select * from Customers", conn);

try

// open the connection

conn.Open();

// 1. get an instance of the SqlDataReader

rdr = cmd.ExecuteReader();

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 41


// print a set of column headers

Console.WriteLine(

"Contact Name City Company Name");

Console.WriteLine(

"------------ ------------ ------------");

// 2. print necessary columns of each

record

while (rdr.Read())

// get the results of each column

string contact = (string)rdr["ContactName"];

string company = (string)rdr["CompanyName"];

string city = (string)rdr["City"];

// print out the results

Console.Write("{0,-25}", contact);

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 42


Console.Write("{0,-20}", city);

Console.Write("{0,-25}", company);

Console.WriteLine();

finally

// 3. close the reader

if (rdr != null)

rdr.Close();

// close the connection

if (conn != null)

conn.Close();

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 43


}

There are dozens of Getxxx methods. These methods read a specific data

type value from a column. For example. GetChar will return a column value as a

character and GetString as a string.

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 44


DATASET WITH C# ADO.NET

In a simple word, A DataSet is a local copy of your Database Table that gets

populated in client PC. It is independent of Data Source and because it exists in the

local system, it makes application fast and reliable. Accessing Remote Database each

time for updating or retrieving details are time-consuming so datasets help you to

keep local database tables on your PC.

A DataSet behaves like real Database and it represents a complete set of data that

includes tables, constraints, and relationships among the tables. Using

the DataAdapters you can fill DataSet and use this dataset for retrieving and

storing information. When all the tasks get completed, update Real Database with

datasets.

A DataSet is an in-memory data store that can hold numerous tables. DataSets only

hold data and do not interact with a data source. It is the SqlDataAdapter that

manages connections with the data source and gives us disconnected behavior. The

SqlDataAdapter opens a connection only when required and closes it as soon as it has

performed its task. For example, the SqlDataAdapter performs the following tasks

when filling a DataSet with data:

1. Open connection

2. Retrieve data into DataSet

3. Close connection

1. Open connection

2. Write changes from DataSet to the data source

3. Close connection

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 45


In between the Fill and Update operations, data source connections are closed and

you are free to read and write data with the DataSet as you need. These are the

mechanics of working with disconnected data. Because the applications hold on to

connections only when necessary, the application becomes more scalable.

A couple scenarios illustrate why you would want to work with disconnected data:

people working without network connectivity and making Web sites more scalable.

Consider salespeople who need customer data as they travel. At the beginning of the

day, they’ll need to sync up with the main database to have the latest information

available. During the day, they’ll make modifications to existing customer data, add

new customers, and input new orders. This is okay because they have a given region

or customer base where other people won’t be changing the same records. At the

end of the day, the salesperson will connect to the network and update changes for

overnight processing.

Another scenario is making a Web site more scalable. With a SqlDataReader, you

have to go back to the database for records every time you show a page. This

requires a new connection for each page load, which will hurt scalability as the

number of users increases. One way to relieve this is to use a DataSet that is

updated one time and stored in the cache. Every request for the page checks the

cache and loads the data if it isn’t there or just pulls the data out of the cache and

displays it. This avoids a trip to the database, making your application more efficient.

Exceptions to the scenario above include situations where you need to update data.

You then have to make a decision, based on the nature of how the data will be used

as to your strategy. Use disconnected data when your information is primarily read-

only, but consider other alternatives (such as using a SqlCommand object for

immediate update) when your requirements call for something more dynamic. Also, if

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 46


the amount of data is so large that holding it in memory is impractical, you will need

to use SqlDataReader for read-only data. Really, one could come up with all kinds of

exceptions, but the true guiding force should be the requirements of your application

which will influence what your design should be.

Creating a DataSet Object

There isn’t anything special about instantiating a DataSet. You just create a new

instance, just like any other object:

DataSet dsCustomers = new DataSet();

The DataSet constructor doesn’t require parameters. However, there is one

overload that accepts a string for the name of the DataSet, which is used if you

were to serialize the data to XML. Since that isn’t a requirement for this example,

I left it out. Right now, the DataSet is empty and you need a SqlDataAdapter to load

it.

WHAT IS DATAADAPTERS?

DataAdapters are used for controlling Datasets and it provides communication

between DataSets and DataSource. DataAdapters make a connection with Data

Source and then Fill Data to DataSets. It also Updates Data Source with DataSets.

IMPORTANT DATA ADAPTERS PROPERTIES AND METHODS

Properties:

Properties Description

DeleteCommand It is used for Deleting Records from DataSource

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 47


InsertCommand It is used for adding New Record to a DataSource

SelectCommand It is used for Selecting Records from a DataSource

UpdateCommand It is used for Updating Records in a DataSource.

TableMapping It is used for mapping actual database tables and datasets.

Methods:

Method Description

Fill This method Fills Records from DataAdapters to DataSets.

Update This method update DataSource with DataSets.

Creating A SqlDataAdapter

The SqlDataAdapter holds the SQL commands and connection object for reading

and writing data. You initialize it with a SQL select statement and connection object:

SqlDataAdapter daCustomers = new SqlDataAdapter("select CustomerID,

CompanyName from Customers", conn);

The code above creates a new SqlDataAdapter, daCustomers. The SQL select

statement specifies what data will be read into a DataSet. The connection

object, conn, should have already been instantiated, but not opened. It is the

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 48


SqlDataAdapter’s responsibility to open and close the connection during Fill and

Update method calls.

As indicated earlier, the SqlDataAdapter contains all of the commands necessary to

interact with the data source. The code showed how to specify the select statement,

but didn’t show the insert, update, and delete statements. These are added to the

SqlDataAdapter after it is instantiated.

There are two ways to add insert, update, and delete commands: via SqlDataAdapter

properties or with a SqlCommandBuilder. We are going to see the easy way of doing

it with the SqlCommandBuilder. In a later lesson, we will also see how to use the

SqlDataAdapter properties, which takes more work but will give you more

capabilities than what the SqlCommandBuilder does. Here’s how to add commands to

the SqlDataAdapter with the SqlCommandBuilder:

SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daCustomers);

Notice in the code above that the SqlCommandBuilder is instantiated with a single

constructor parameter of the SqlDataAdapter,daCustomers, instance. This tells the

SqlCommandBuilder what SqlDataAdapter to add commands to. The

SqlCommandBuilder will read the SQL select statement (specified when the

SqlDataAdapter was instantiated), infer the insert, update, and delete commands,

and assign the new commands to the Insert, Update, and Delete properties of the

SqlDataAdapter, respectively.

As I mentioned earlier, the SqlCommandBuilder has limitations. It works when you

do a simple select statement on a single table. However, when you need a join of two

or mor tables or must do a stored procedure, it won’t work.

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 49


Filling the DataSet

Once you have a DataSet and SqlDataAdapter instances, you need to fill the

DataSet. Here’s how to do it, by using the Fill method of the SqlDataAdapter:

daCustomers.Fill(dsCustomers, "Customers");

The Fill method, in the code above, takes two parameters: a DataSet and a table

name. The DataSet must be instantiated before trying to fill it with data. The second

parameter is the name of the table that will be created in the DataSet. You can name

the table anything you want. Its purpose is so you can identify the table with a

meaningful name later on. Typically, I’ll give it the same name as the database table.

However, if the SqlDataAdapter’s select command contains a join, you’ll need to find

another meaningful name.

The Fill method has an overload that accepts one parameter for the DataSet only.

In that case, the table created has a default name of “table1” for the first table.

The number will be incremented (table2, table3, …, tableN) for each table added to

the DataSet where the table name was not specified in the Fill method.

Using the DataSet

A DataSet will bind with both ASP.NET and Windows forms DataGrids. Here’s an

example that assigns the DataSet to a Windows forms DataGrid:

dgCustomers.DataSource = dsCustomers;

dgCustomers.DataMember = "Customers";

The first thing we do, in the code above, is assigned the DataSet to the DataSource

property of the DataGrid. This lets the DataGrid know that it has something to bind

to, but you will get a ‘+’ sign in the GUI because the DataSet can hold multiple tables

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 50


and this would allow you to expand each available table. To specify exactly which

table to use, set the DataGrid’s DataMember property to the name of the table. In

the example, we set the name to Customers, which is the same name used as the

second parameter to the SqlDataAdapter Fill method. This is why I like to give the

table a name in the Fill method, as it makes the subsequent code more readable.

Updating Changes

After modifications are made to the data, you’ll want to write the changes back to

the database. Refer to the previous discussion in the Introduction of this chapter

on update guidance. The following code shows how to use the Update method of the

SqlDataAdapter to push modifications back to the database.

daCustomers.Update(dsCustomers, "Customers");

The Update method, above, is called on the SqlDataAdapter instance that originally

filled the dsCustomers DataSet. The second parameter to the Update method

specifies which table, from the DataSet, to update. The table contains a list of

records that have been modified and the Insert, Update, and Delete properties of

the SqlDataAdapter contain the SQL statements used to make database

modifications.

Programming Example in C# Console:

using System;

1. using System.Data.SqlClient;

2. using System.Data;

3.

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 51


4. namespace DataSet_Example

5. {

6. class Program

7. {

8. static void Main(string[] args)

9. {

10. string ConString = @"Data Source=.\SQLEXPRESS;Initial

Catalog=ComputerShop;Integrated Security=True";

11. string querystring = "Select * from Items";

12. SqlDataAdapter adapter = new SqlDataAdapter(querystring,

ConString);

13. DataSet ds = new DataSet();

14. adapter.Fill(ds, "Items");

15. Console.WriteLine(ds.GetXml());

16. Console.ReadKey();

17. }

18. }

19. }

Output

1.

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 52


2.

3. 1

4. LED Screen

5. $120

6. 2017-01-27T00:00:00+05:30

7.

8.

9. 2

10. USB Keyboard

11. $20

12. 2017-05-25T00:00:00+05:30

13.

14.

DATASET EXAMPLE WITH GRID VIEW

Mostly DataSet is used with GridView in ASP.Net. Here, I have explained

DataAdapters and DataSets with Examples.

1. Open Visual Studio and Go to File > New >

Project. Create a New Windows Forms Application Dataset_Example.

2. Drag a GridView and a Button like that.

Extract Data from DataSet to GridView

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 53


1. using System;

2. using System.Data;

3. using System.Data.SqlClient;

4. using System.Windows.Forms;

5. namespace DataSet_Exampl

6. {

7. public partial class Form1 : Form

8. {

9. public Form1()

10. {

11. InitializeComponent();

12. }

13.

14. private void btnGetData_Click(object sender, EventArgs e)

15. {

16. string ConString = @"Data Source=.\SQLEXPRESS;Initial

Catalog=ComputerShop;Integrated Security=True";

17. string Query = "SELECT * FROM Items";

18.

19. SqlDataAdapter adapter = new SqlDataAdapter(Query,ConString);

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 54


20. DataSet set = new DataSet();

21.

22. adapter.Fill(set, "Items");

23. dataGridView1.DataSource = set.Tables["Items"];

24. }

25. }

26. }

Output

UPDATING, INSERTING, AND DELETING RECORDS IN A DATASET

After populating dataset, you can update, insert or delete a record from the dataset.

Here is a full programming example.

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 55


Adding New Row in DataTable

1. private void btnInsert_Click(object sender, EventArgs e)

2. {

3. //Fill Dataset

4. string ConString = @"Data Source=.\SQLEXPRESS;Initial

Catalog=ComputerShop;Integrated Security=True";

5. string Query = "SELECT * FROM Items";

6. SqlDataAdapter adapter = new SqlDataAdapter(Query, ConString);

7. DataSet set = new DataSet();

8. adapter.Fill(set, "Items");

9.

10. //Adding New Row to DataSet

11. DataRow row = set.Tables["Items"].NewRow();

12. row["Name"] = "4GB DDR3 RAM";

13. row["Price"] = "$50";

14. row["Date"] = "26 May 2017";

15. set.Tables["Items"].Rows.Add(row);

16.

17. dataGridView1.DataSource = set.Tables["Items"];

18. }

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 56


Output

Insert Row in Dataset

Edit or Update Row in DataSet

If you don’t know row index or unique row number still you can update or edit row in

dataset by using following method.

1. private void btnUpdate_Click(object sender, EventArgs e)

2. {

3. //Fill Dataset

4. string ConString = @"Data Source=.\SQLEXPRESS;Initial

Catalog=ComputerShop;Integrated Security=True";

5. string Query = "SELECT * FROM Items";

6. SqlDataAdapter adapter = new SqlDataAdapter(Query, ConString);

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 57


7. DataSet set = new DataSet();

8. adapter.Fill(set, "Items");

9.

10. set.Tables["Items"].Rows[1]["Name"] = "Graphics Card";

11.

12. dataGridView1.DataSource = set.Tables["Items"];

13. }

Output

Delete Row in DataSet

You can delete row from dataset using Delete() Method.

1. private void btnDelete_Click(object sender, EventArgs e)

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 58


2. {

3. //Fill Dataset

4. string ConString = @"Data Source=.\SQLEXPRESS;Initial

Catalog=ComputerShop;Integrated Security=True";

5. string Query = "SELECT * FROM Items";

6. SqlDataAdapter adapter = new SqlDataAdapter(Query, ConString);

7. DataSet set = new DataSet();

8. adapter.Fill(set, "Items");

9.

10. set.Tables["Items"].Rows[1].Delete();

11.

12. dataGridView1.DataSource = set.Tables["Items"];

13. }

Output

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 59


SAVE DATASET CHANGES TO DATABASE

After Modifying Dataset, you can save Dataset changes to database.

Programming Example

1. private void btnSave_Click(object sender, EventArgs e)

2. {

3. //Fill Dataset

4. string ConString = @"Data Source=.\SQLEXPRESS;Initial

Catalog=ComputerShop;Integrated Security=True";

5. string Query = "SELECT * FROM Items";

6. SqlDataAdapter adapter = new SqlDataAdapter(Query, ConString);

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 60


7. DataSet set = new DataSet();

8. adapter.Fill(set, "Items");

9.

10. //Adding New Row to DataSet and Update

11. DataRow row = set.Tables["Items"].NewRow();

12. row["Name"] = "4GB DDR3 RAM";

13. row["Price"] = "$50";

14. row["Date"] = "26 May 2017";

15. set.Tables["Items"].Rows.Add(row);

16.

17. //Updating Database Table

18. SqlCommandBuilder builder = new SqlCommandBuilder(adapter);

19. adapter.Update(set.Tables["Items"]);

20.

21. MessageBox.Show("DataSet Saved to Database Successfully");

22.

23. }

Output

DataSet Saved to Database Successfully _

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 61


DATAVIEWS WITH C# ADO.NET

DataView gives option to display DataTable’s data in various style, views or format.

With DataView you can display data with various sorting order, customization and

filtration. In this tutorial you will learn everything about DataView in C# ADO.Net.

CREATING AND DISPLAYING A DATAVIEW

1. private void btnDisplay_Click(object sender, EventArgs e)

2. {

3. string ConString = @ "Data Source=.\SQLEXPRESS;Initial Catalog=ComputerShop;

Integrated Security=True";

4. string Query = "SELECT * FROM Items";

5.

6. SqlDataAdapter adapter = new SqlDataAdapter(Query, ConString);

7. DataSet set = new DataSet();

8.

9. adapter.Fill(set, "Items");

10. DataView dv = set.Tables["Items"].DefaultView;

11. dataGridView1.DataSource = dv;

12. }

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 62


Output

Adding Row in DataView

1. private void btnAdd_Click(object sender, EventArgs e)

2. {

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 63


3. string ConString = @ "Data Source=.\SQLEXPRESS;Initial Catalog=ComputerShop;

Integrated Security=True";

4. string Query = "SELECT * FROM Items";

5.

6. SqlDataAdapter adapter = new SqlDataAdapter(Query, ConString);

7. DataSet set = new DataSet();

8.

9. adapter.Fill(set, "Items");

10. DataView dv = set.Tables["Items"].DefaultView;

11. dv.AllowNew = true;

12. DataRowView newRow = dv.AddNew();

13. newRow.BeginEdit();

14. newRow["Name"] = "Router";

15. newRow["Price"] = "$130";

16. newRow["Date"] = "26 August 2016";

17. newRow.EndEdit();

18. dataGridView1.DataSource = dv;

19. }

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 64


Output

Editing or Updating Row in DataView

1. private void btnEdit_Click(object sender, EventArgs e)

2. {

3. string ConString = @ "Data Source=.\SQLEXPRESS;Initial Catalog=ComputerShop;

Integrated Security=True";

4. string Query = "SELECT * FROM Items";

5.

6. SqlDataAdapter adapter = new SqlDataAdapter(Query, ConString);

7. DataSet set = new DataSet();

8.

9. adapter.Fill(set, "Items");

10. DataView dv = set.Tables["Items"].DefaultView;

11. dv.AllowEdit = true;

12. dv[1].BeginEdit();

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 65


13. dv[1]["Name"] = "WireLess Keyboard";

14. dv[1]["Price"] = "$88";

15. dv[1].EndEdit();

16.

17. dataGridView1.DataSource = dv;

18. }

Output

Deleting Row from DataView

1. private void btnDelete_Click(object sender, EventArgs e)

2. {

3. string ConString = @ "Data Source=.\SQLEXPRESS;Initial Catalog=ComputerShop;

Integrated Security=True";

4. string Query = "SELECT * FROM Items";

5.

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 66


6. SqlDataAdapter adapter = new SqlDataAdapter(Query, ConString);

7. DataSet set = new DataSet();

8.

9. adapter.Fill(set, "Items");

10. DataView dv = set.Tables["Items"].DefaultView;

11. dv.AllowDelete = true;

12. dv.Table.Rows[2].Delete();

13.

14. dataGridView1.DataSource = dv;

15. }

Output

ADO.NET, by Mr. SILAS.N.T., NPUI BAMENDA pg. 67

You might also like