0% found this document useful (0 votes)
15 views

UNit 5 ADO.NET

ADO.NET is a framework that facilitates data access between front-end applications and back-end databases, utilizing key classes such as Connection, Command, DataReader, DataAdapter, and DataSet. It supports both direct and disconnected data access, allowing for efficient data manipulation and retrieval while promoting features like interoperability, maintainability, and scalability. However, it has limitations such as compatibility issues with non-Windows platforms and potential complexity in managing database interactions.

Uploaded by

Vimal Cheyyar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

UNit 5 ADO.NET

ADO.NET is a framework that facilitates data access between front-end applications and back-end databases, utilizing key classes such as Connection, Command, DataReader, DataAdapter, and DataSet. It supports both direct and disconnected data access, allowing for efficient data manipulation and retrieval while promoting features like interoperability, maintainability, and scalability. However, it has limitations such as compatibility issues with non-Windows platforms and potential complexity in managing database interactions.

Uploaded by

Vimal Cheyyar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

ADO.

NET Fundamentals
ADO.NET provides a bridge between the front end controls and the back end database. The
ADO.NET objects encapsulate all the data access operations and the controls interact with
these objects to display data, thus hiding the details of movement of data.

The following figure shows the ADO.NET objects at a glance:

Important Classes in ADO.NET

1. Connection Class

2. Command Class

3. DataReader Class

4. DataAdaptor Class

5. DataSet.Class

1. Connection Class

In ADO.NET, we use these connection classes to connect to the database. These connection
classes also manage transactions and connection pooling. To learn more about connection
classes, start here: Connection in ADO.NET.

2. Command Class
The Command class provides methods for storing and executing SQL statements and Stored
Procedures. The following are the various commands that are executed by the Command Class.

ExecuteReader: Returns data to the client as rows. This would typically be an SQL select
statement or a Stored Procedure that contains one or more select statements. This method
returns a DataReader object that can be used to fill a DataTable object or used directly for
printing reports and so forth.

ExecuteNonQuery: Executes a command that changes the data in the database, such as an
update, delete, or insert statement, or a Stored Procedure that contains one or more of these
statements. This method returns an integer that is the number of rows affected by the query.

ExecuteScalar: This method only returns a single value. This kind of query returns a count of
rows or a calculated value.

ExecuteXMLReader: (SqlClient classes only) Obtains data from an SQL Server 2000 database
using an XML stream. Returns an XML Reader object.

3. DataReader Class

The DataReader is used to retrieve data. It is used in conjunction with the Command class to
execute an SQL Select statement and then access the returned rows. Learn more here: Data
Reader in C#.

4. DataAdapter Class

The DataAdapter is used to connect DataSets to databases. The DataAdapter is most useful
when using data-bound controls in Windows Forms, but it can also be used to provide an easy
way to manage the connection between your application and the underlying database tables,
views and Stored Procedures. Learn more here: Data Adapter in ADO.NET.

5. DataSet Class

The DataSet is the heart of ADO.NET. The DataSet is essentially a collection of DataTable
objects. In turn each object contains a collection of DataColumn and DataRow objects. The
DataSet also contains a Relations collection that can be used to define relations among Data
Table Objects.

Features of ADO.NET :

The following are the features of ADO.NET –

1. Interoperability-We know that XML documents are text-based formats. So, one can edit
and edit XML documents using standard text-editing tools. ADO.NET uses XML in all data
exchanges and for internal representation of data.

2. Maintainability – ADO.NET is built around the idea of separation of data logic and user
interface. It means that we can create our application in independent layers.

3. Programmability (Typed Programming) – It is a programming style in which user words


are used to construct statements or evaluate expressions. For example: If we want to
select the “Marks” column from “Kawal” from the “Student” table, the following is the
way to do so:
DataSet.Student("Kawal").Marks;

4. Performance – It uses disconnected data architecture which is easy to scale as it reduces


the load on the database. Everything is handled on the client-side, so it improves
performance.

5. Scalability – It means meeting the needs of the growing number of clients, which
degrading performance. As it uses disconnected data access, applications do not retain
database lock connections for a longer time. Thus, it accommodates scalability by
encouraging programmers to conserve limited resources and allow users to access data
simultaneously.

Advantages

 Efficient data access: ADO.NET provides a way to access data from a variety of sources,
including SQL Server and XML

 Robust architecture: ADO.NET has a strong architecture and a rich component object
model

 Support for multiple data providers: ADO.NET supports many data providers, including
OLE DB and ODBC

 XML integration: ADO.NET supports XML, which is a common format for sharing data
between applications

 Scalability: ADO.NET can scale to serve more clients without degrading performance

 Interoperability: ADO.NET can communicate across different environments

Disadvantages

 Limited support for non-Windows platforms: ADO.NET may not be compatible with
non-Windows platforms

 May require additional configuration: ADO.NET may require additional configuration for
fine-grained security

 May require more memory and disk space: ADO.NET applications may require more
memory and disk space

Configure your Database


ADO.NET doesn't directly "configure" your database in the sense of creating databases, tables,
or altering schema. Its role is to provide a managed .NET framework for accessing and
manipulating data already stored in a database. The database configuration itself happens
outside of ADO.NET, typically using tools specific to your database system (e.g., SQL Server
Management Studio for SQL Server, phpMyAdmin for MySQL, pgAdmin for PostgreSQL).

However, ADO.NET plays a crucial role in how your .NET application interacts with a configured
database. Let's break down the key aspects of using ADO.NET with your database:

1. Choosing a Data Provider:

 ADO.NET isn't a single monolithic component. It provides a framework, and specific data
providers are needed to connect to different database systems. The most common ones
include:

 SqlClient: For connecting to Microsoft SQL Server.

 OleDb: A more general-purpose provider that supports a wide range of databases


(though often less efficient than dedicated providers).

 Odbc: Another general-purpose provider, relying on ODBC drivers.

 OracleClient: For Oracle databases (now largely superseded by using ODP.NET).

 MySqlConnector: A popular and performant provider for MySQL.

 Npgsql: For PostgreSQL databases.

The choice depends entirely on your database system. You'll need to install the appropriate
NuGet package for your chosen provider in your .NET project.

2. Connection Strings:
The connection string is the crucial piece of information that tells ADO.NET how to connect to
your database. It includes details like:

 Server: The address (IP or hostname) of your database server.

 Database: The name of the specific database you want to access.

 User ID: The username for authentication.

 Password: The password for the user.

 Integrated Security: (Often preferred for development) Enables Windows


Authentication, using the current user's credentials.

Example Connection String (SqlClient for SQL Server):

C#

string connectionString = "Server=myServerAddress;Database=myDataBase;User


Id=myUsername;Password=myPassword;";

// Or using Integrated Security:

string connectionString = "Server=myServerAddress;Database=myDataBase;Integrated


Security=True;";

```

3. Connecting and Executing Commands:

Once you have your connection string, you use ADO.NET classes to connect, execute
commands, and process results. Common classes include:

 SqlConnection (SqlClient): Represents a connection to a SQL Server database.

 SqlCommand: Represents a SQL command to be executed.

 SqlDataReader: Used to read the results of a query.

 SqlDataAdapter: Used to fill a `DataSet` or `DataTable` with data.

 Transactions: For ensuring data integrity by grouping multiple operations into a single
atomic unit.

Example (using SqlClient and `SqlDataReader`):


C#

using (SqlConnection connection = new SqlConnection(connectionString))

connection.Open();

using (SqlCommand command = new SqlCommand("SELECT FROM MyTable", connection))

using (SqlDataReader reader = command.ExecuteReader())

while (reader.Read())

// Process each row

Console.WriteLine(reader["ColumnName"]);

```

4. Data Access Patterns:

Different patterns are used depending on the needs of our application:

 DataReaders: Efficient for reading data sequentially, suitable for reporting or displaying
lists.

 DataAdapters/DataSets/DataTables: For working with data in a disconnected manner,


suitable for applications needing offline capabilities or complex data manipulation.

 ORM (Object-Relational Mapping): Frameworks like Entity Framework Core abstract


away much of the ADO.NET interaction, providing a more object-oriented approach to
database access. They manage the connection, commands, and data mapping for you.
5. Error Handling and Security:

Proper error handling is vital. Always use `try-catch` blocks to handle potential exceptions (e.g.,
`SqlException`). Security is equally important. Never hardcode sensitive information like
connection strings directly into your code; use configuration files or secure storage mechanisms
instead. Parameterization of SQL queries is crucial to prevent SQL injection vulnerabilities.

Direct Data Access with ADO.NET

ADO.NET is a core component of the .NET Framework that provides a set of classes for interacting with
data sources such as databases, XML files, and more. It establishes a bridge between the front end of an
application and the back end where data is stored.

Direct data access with ADO.NET involves directly interacting with a database using the ADO.NET classes
without relying on an Object-Relational Mapper (ORM) or other abstraction layers. This provides
maximum control and efficiency, but requires a deeper understanding of SQL and database interactions.
Let's break down the key aspects:

1. Core Components:

`SqlConnection`: Establishes the connection to the database. Requires a connection string specifying the
server, database name, user credentials, and other relevant information.

`SqlCommand`: Represents a SQL command to be executed against the database. This includes queries
(SELECT), insertions (INSERT), updates (UPDATE), and deletions (DELETE). It can also handle stored
procedures.
`SqlDataReader`: Used to read the results of a SELECT query. Iterates row by row, allowing access to
individual columns using their name or index.

`SqlDataAdapter`: Acts as a bridge between the `DataSet` or `DataTable` and the database. It fetches
data, updates data, and manages changes. While technically not direct access in the purest sense, it's
frequently used with direct data access for simplifying data handling.

`DataSet` and `DataTable`: In-memory representations of data fetched from the database. `DataSet` can
contain multiple `DataTable` objects, allowing for managing related data. These are less commonly used
in modern, leaner applications, often superseded by other data handling techniques.

2. Basic Workflow:

1. Connection: Create a `SqlConnection` object and open the connection using `Open()`.

2. Command: Create a `SqlCommand` object, specifying the SQL statement and the connection object.
Add parameters if needed to prevent SQL injection vulnerabilities.

3. Execution: Execute the command using appropriate methods:

`ExecuteReader()` for SELECT statements, returning a `SqlDataReader`.

`ExecuteNonQuery()` for INSERT, UPDATE, and DELETE statements, returning the number of affected
rows.

`ExecuteScalar()` for queries returning a single value.

4. Data Processing: For SELECT statements, read the data from the `SqlDataReader` and process it. For
other statements, handle the return value accordingly.

5. Closing: Close the `SqlDataReader` (if used) and the `SqlConnection` using `Close()`. This is crucial for
releasing database resources.

3.Connecting to the Database

using System.Data.SqlClient;

// Create a connection string

string connectionString = "Server=myServerAddress;Database=myDataBase;User


Id=myUsername;Password=myPassword;";

try

// Create a connection object


using (SqlConnection connection = new SqlConnection(connectionString))

// Open the connection

connection.Open();

// Create a command object

using (SqlCommand command = new SqlCommand("SELECT FROM MyTable", connection))

// Execute the query and get a DataReader

using (SqlDataReader reader = command.ExecuteReader())

// Read data from the DataReader

while (reader.Read())

Console.WriteLine(reader["ColumnName1"] + ", " + reader["ColumnName2"]);

catch (SqlException ex)

Console.WriteLine("Error: " + ex.Message);

// Close the connection

connection.Close();
``

4. Using DataSets and DataAdapters

DataSet

A DataSet can be considered as a kind of cache, or in-memory data storage. We use an adapter (such as
SqlDataAdapter) to retrieve data from the database and store it in the Dataset, then we close the
connection to the database. We can then make work with the data, even make changes to it within the
DataSet, and then update the database with the changes using a new connection. It is worth noting that
during the time between retrieval and update anyone can modify the same data in the database, thus
the disadvantages of DataSet is having to manage conflicts and concurrent data access issues covered
previously in transaction management.

The steps of working with a DataSet:

Open a connection

Fill the DataSet with part of the database

Close the connection

Work with the DataSet (e.g., display and edit in a user interface) - this may take longer

Open a new connection

Synchronize changes

Close the connection

To work with disconnected data, `DataSets` and `DataAdapters` come into play. They enable you to
retrieve data into a `DataSet`, manipulate it in memory, and then persist the changes back to the
database.

C#

SqlDataAdapter adapter = new SqlDataAdapter("SELECT FROM Users", connection);

DataSet dataSet = new DataSet();

adapter.Fill(dataSet, "Users");

// Modify data in the DataSet

DataTable usersTable = dataSet.Tables["Users"];

DataRow newRow = usersTable.NewRow();


newRow["Name"] = "New User";

usersTable.Rows.Add(newRow);

// Update the database

SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adapter);

adapter.Update(dataSet, "Users");

```

5. Error Handling

Error handling is crucial when dealing with database operations to manage unexpected exceptions
gracefully. A common approach is to use try-catch blocks to capture SQL exceptions.

C#

try

// Database operations here

catch (SqlException ex)

Console.WriteLine($"SQL Error: {ex.Message}");

catch (Exception ex)

Console.WriteLine($"General Error: {ex.Message}");

```

4. Advantages of Direct Data Access:

Performance: Can be more efficient than ORMs for specific queries, especially complex ones.
Control: Offers granular control over database interactions, allowing for optimization and fine-tuning.

Flexibility: Enables the execution of any SQL statement, including complex queries and stored
procedures.

5. Disadvantages of Direct Data Access:

Complexity: Requires a deep understanding of SQL and database concepts.

Maintainability: Can be harder to maintain as the application grows, especially if the database schema
changes frequently.

Security: Requires careful handling of parameters to prevent SQL injection attacks. Parameterized
queries are essential.

Data Mapping: You are responsible for manually mapping data from the database to your application
objects.

Disconnected Data Access With ADO.NET


ADO.NET is a core component of the .NET Framework that enables data access and
manipulation. One of its most powerful features is the concept of "disconnected data access,"
which allows applications to interact with data sources without needing a constant connection.
This is particularly useful in scenarios where persistent connections are not suitable due to
performance, scalability, or network issues.

In ADO.NET, "disconnected data access" refers to the ability to retrieve data from a database,
store it in memory using objects like DataSet and DataTable, and manipulate that data without
maintaining an active connection to the database, essentially allowing you to work with data
"offline" by processing it within your application without constant database interaction.

1. Disconnected Architecture:
- ADO.NET supports the disconnected architecture through the use of datasets and data
adapters. In this architecture, data is retrieved from the database and stored locally in memory,
allowing applications to work with the data without a continuous connection to the database.

2. DataSet:

- The `DataSet` is an in-memory representation of data that can hold multiple tables,
relationships, and constraints. It acts as a container for data retrieved from the database,
enabling complex structures that can include parent-child relationships among tables.

3. DataAdapter:

- The `DataAdapter` serves as a bridge between the `DataSet` and the database. It is responsible
for filling the `DataSet` with data using the `Fill` method and then sending any modifications
(such as inserts, updates, or deletes) back to the database using the `Update` method.

Methods of Data Adpter

Fill (DataSet ds,string TableName).

Update (DataSet ds,string TableName)

Fill in the method to load data from a DataSource into a DataSet.

Update is to transfer data from a DataSet to a DataSource.

DataAdapter is internally a collection of the following 4 methods:

 Select Command.

 Insert Command.

 Update Command.
 Delete Command.

When we call the Fill() method of Adapter, the following action takes place internally.

Open a connection with the DataSource.

Execute the Select command under it on the DataSource and loads data from the table to the
DataSet.

Close the Connection.

Siince a DataSet is updatable, changes can be made to data that is loaded into it, like adding,
modifying and deleting records.

After making all the changes to the data in a dataset if we want to send those changes back to
the DataSource then call the Update() method on the DataAdapter that performed the
following:

 Re-opened a connection with the DataSource.

 Changes made in the dataset will be sent back to the table where in this process it will
use the insert, update and delete commands of the DataAdapter.

 Close the Connection.

4. DataTable:

- Each individual table within a `DataSet` is represented by a `DataTable`. This is where


individual data rows are stored and can be manipulated with various methods and properties.

DataRow

It is a collection of rows.

Syntax:

<datatable>.Rows[Index].

For example:

Ds.tables[0].rows[0]

DataColumns

It is a collection of Columns.

Syntax:
<datatable>.Columns[Index] OR columns[Name]

For example:

Ds.Tables[0].Column[0]

Or:

Ds.Tables*0+.Column*“ENO”+

Ds.tables[0].rows[0]

How it works:

1. Connect and retrieve data:

Establish a connection to the database using a SqlConnection and use a DataAdapter to fetch
data from the database and populate a DataSet.

2. Disconnect and manipulate data:

Once the DataSet is filled, the connection to the database can be closed. You can then modify
the data within the DataSet tables as needed.

C#

using (SqlConnection connection = new SqlConnection(connectionString))

SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT FROM Employees", connection);

DataSet dataSet = new DataSet();

dataAdapter.Fill(dataSet, "Employees");

...

3. Update database (if necessary):

When ready to save changes, use the DataAdapter to update the database based on the
changes made in the DataSet.

Example:-
In ADO.NET, disconnected data access means fetching data from a database, working with it
in-memory (using DataSet, DataTable, or DataView), and not maintaining an active connection
to the database.

DataView operates on a DataTable, which is disconnected from the database once data is
retrieved. Below is a demonstration proving that DataView works without a continuous
database connection.

using System;

using System.Data;

using System.Data.SqlClient;

class Program

static void Main()

// Connection string (Modify based on your database)

string connectionString = "Server=your_server;Database=your_db;Integrated


Security=True;";

// Disconnected data access: Fetch data once, then close connection

DataTable dt = new DataTable();

using (SqlConnection conn = new SqlConnection(connectionString))

conn.Open();

string query = "SELECT ID, Name, Age FROM Employees"; // Fetch data from
DB
SqlDataAdapter adapter = new SqlDataAdapter(query, conn);

adapter.Fill(dt); // Data loaded into DataTable (Disconnected)

conn.Close(); // Connection is now closed

// Proof: Data is stored in-memory. We no longer need the database connection.

Console.WriteLine("Database Connection is Closed!");

Console.WriteLine($"Total Rows Retrieved: {dt.Rows.Count}");

// Creating DataView from DataTable

DataView dv = new DataView(dt);

// Apply Sorting

dv.Sort = "Age ASC";

// Apply Filtering (Only employees older than 25)

dv.RowFilter = "Age > 25";

// Display Data (Working without DB connection)

Console.WriteLine("\nFiltered Employees (Age > 25):");

foreach (DataRowView row in dv)

Console.WriteLine($"ID: {row["ID"]}, Name: {row["Name"]}, Age: {row["Age"]}");

}
// Proving disconnection: Modify DataView without any DB connection

DataRowView newRow = dv.AddNew();

newRow["ID"] = 999;

newRow["Name"] = "John Doe";

newRow["Age"] = 35;

newRow.EndEdit();

Console.WriteLine("\nNew Row Added (Without DB Connection):");

foreach (DataRowView row in dv)

Console.WriteLine($"ID: {row["ID"]}, Name: {row["Name"]}, Age: {row["Age"]}");

Advantages of Disconnected Access:

Improved Performance: Reduces the load on the database server, particularly in situations with
many concurrent users or large datasets.

Offline Capabilities: Allows applications to function even without a persistent database


connection.

Data Integrity: Provides a mechanism for managing transactions and ensuring data consistency
through the `Update()` method.

Scalability: More scalable than connected architecture as it reduces database server


contention.

Enhanced UI Responsiveness: Because the connection is closed, UI doesn't block while waiting
for database operations.
Disadvantages of Disconnected Access:

Increased Memory Usage: The `DataSet` holds a complete copy of the data in memory,
potentially consuming significant resources.

Data Consistency Issues: If multiple users update the same data concurrently without proper
concurrency control, conflicts can arise. Optimistic concurrency checks are often used to
mitigate this.

Complexity: Managing the `DataSet`, `DataTable`, `DataAdapter`, and related objects can add
complexity to the application code.

Potential for Stale Data: If data is updated in the database while the application is working with
a disconnected `DataSet`, the application may be working with outdated information.

Data Binding With ADO.NET


The user can bind values to the respective controls in ADO.NET. Depending on the type of
binding offered, they are distinguished as follows:

Simple Data Binding

Complex Data Binding

1. Simple Data Binding

The Simple Data Binding is the process of binding the control with the single value in the
dataset. The controls like text box, label can be bound to the control through the control
properties.

Consider an example to display the result of the students in an examination. The details are
added in the following format.

 Create a Windows Form Application in Visual Studio .NET. The following customized
format is created for user.
 Once the design of the form is created, select the View option from the menu bar. Click
on the Properties window.

 Select the first text box and the properties for it appear in the window.

 Expand the DataBindings property

 Select the Text property for enabling the drop down list.

 Click the Add Project Data Source from the drop down list

 Make a connection with the CurrentInfo database and select the Student table

 Select the Other Data Sources, Project Data Sources, CurrentInfoDataSet, Student table.

 Select the Name column and bind it with the textbox.

 Bind all the other text boxes with the database values.

 Press F5 and execute the Windows Form.

12.The following output is displayed to the user.


2. Complex Data Binding

The Complex Data Binding is the process of binding the component with the Database. The
controls can be GridView, Dropdown list, or combo box. Multiple values can be displayed from
the dataset through the binding.

The controls that can be used for binding the multiple values from the database to the
Windows Form are listed below.

 DataGridView: It is used to display the multiple records and columns. The DataSource
property of the DataGridView control is used for binding the specific data element.

 ComboBox: The control contains a text box for entering the data and drop down list for
displaying the values. The DataSource property is useful for binding the control. The
element specific information can be bind through the DisplayMember property

 ListBox: It is used for displaying the data for the column from several records of
datasets. The DataSource property is used for binding the control to the data source.

 The DisplayMember property is used for binding the control to the specific data
element.

Navigating Records in ADO.NET


A BindingNavigator control is used for handling the binding to the data source through the
pointer to the current item in the list of records.

The navigator control is used with the BindingSource control for enabling the users to navigate
the data records on a form. It provides a layer between the controls and windows form of the
data source. Users can navigate and modify the records in the Windows form.

The following figure displays the BindingNavigator control and the BindingSource control in the
Windows Form.

The Binding Navigator control has many controls for modifying the data source. The list of
controls and their functions are mentioned below:

 bindingNavigatorAddNewItem Button: The + sign indicates that the new row can be
added to the data source.

 bindingNavigatorDeleteItem Button: The X sign indicates that the current row can be
deleted from the data source.

 bindingNavigatorMoveFirstItem Button: The button indicates that the user can move to
the first item in the data source.

 bindingNavigatorMoveLastItem Button: The button indicates that the user can move to
the last item in the data source

 bindingNavigatorMoveNextItem Button: The button indicates that the user can move to
the next item in the data source

 bindingNavigatorMovePreviousItem Button: The button indicates that the user can


move to the previous item in the data source

 bindingNavigatorPositionItem textbox: The returns current position in the data source

 bindingNavigatorCountItemText box: The is used to return the total number of items in


the data source.

Consider the Order details table containing the data about the orders to be added. The data is
organized into a format as shown below:

 Open Visual studio application and add Windows Forms Application from the template
pane.

 Add the labels and a binding Navigator control, and textbox controls to the form

 Click OK button

 Click View, Properties Window, and open the Properties Window.

5.Add the appropriate names to the controls present in the web form.

6. Open the Data Source Configuration Wizard. The Database icon must be selected. Click
Next Button
7. Click New Connection Button. Add Connection dialog box is shown.
8. Add the Server Name, select Use SQL Server Authentication option from the Log on the
server section
9. Add the User name as sa and password as abcd1234
10. Select the Order Details database and click Test Connection button
11. Click OK and close the Add Connection dialog box
12. Click Next button. In the Choose Your Database Objects dialog box, expand Tables node.
13. Select the Orderdata table and click Finish button.
For binding the data to the control in the Windows Form, the following steps are executed.

 Select the textbox1, and expand the DataBindings property.

 Select the Text property and click on the drop down list.

 1Expand the Other Data Sources, Project Data, Sources, Orderdataset, Orderdata nodes.

 Select the OrderID column and bind it with textbox1.

 Perform the similar operations for all the textboxes.

Press F5 or click Debug -> Start Debugging option from the menu. The Order Details form is
displayed as shown below:

User can navigate through the other records using the navigator button of the control.
Close the form and exit the Visual Studio application.

Filtering Data

There are requirements when user wants to display only limited data to the client. The filtering
of data is possible for displaying the desired results. The data can be sorted in ascending or
descending order.
There are two ways by which the data can be filtered. They are as mentioned below:

 Parameterized Queries

 Filtering data using controls in Windows Form.

1. Parameterized Queries

The stored procedures are always useful for accessing data from the database. By using the
stored procedures users can precompiled execution, use of code, less network traffic, and
security is high for the data stored in the system.

The parameterized queries are useful for filtering the data based on the conditions defined by
the user at runtime. They are useful when user wants to execute the data based on the
situation.

The following query is useful for selecting the student with the ID specified.

Code:

SELECT StudName FROM Student

WHERE StudID = @StudID

In the above code, the @StudID is the parameter in the query. The value is passed at the
runtime by the user.

In ADO.NET, for populating the @StudID parameter, the SqlParameter object in the
SqlParameter class for the command. The SqlParameter object is used for assigning the
parameterized values to the queries.

Consider the example for extracting the details of the student. The following code shows the
execution parameterized query.

Code:

SqlConnection con = new SqlConnection();


con.ConnectionString = “DataSource = SQLSERVER02; Initial Catalog=StudData; User ID = sa;
Password=abcd1234”;

con.Open();

string studid;

studid = textbox1.Text;

String query = “ SELECT * from StudData where StudID = @StudID”;

SqlCommand cmd = new SqlCommand( query, con);

cmd.Parameters.Add( new SqlParameter ( “@StudID”, StudID ) );

SqlDataReader dr = cmd.ExecuteReader();

2. Filtering data using controls in Windows Form

Once the data is retrieved from the data source by binding the data to the control of the
Windows form, the data filter is used for displaying the selective records.

Consider the example of a company where user wants to view the information about the
employee data. The information is displayed in the form of a grid view. The connection is
established with the database and the data binding through the DataGridView control.

If user wants the data only of the specific employees in the organization, they can be filtered
using the following steps.

Select the DataGridView control in the form and open the DataGridViewTasks window.

Click on the Add Query option. The SearchCriteria Builder dialog box will open.

Add the following query in the query text box.

Code:

SELECT EmpID, EmpName, EmpRole FROM Employee WHERE ( EmpID = 101 )

Click on the Query Builder button

Click on the Execute Query button. The output generated by the query can be checked
Click OK button and close the Search Criteria Builder dialog box

Press F5 and execute the Windows Form.

In the above example, TableAdapter queries are the SQL statements or procedures that are
executed. The FillBy method is useful for executing the TableAdapter queries.

The following code can be added to the Click event of the FillByToolStrip control.

Code:

private void fillByToolStripButton_Click( object sender, EventArgs e )

try

this.internalCandidateTableAdapter.FillBy( this.EmpDataSet.Employee);

catch( System.Exception ex )

System.Windows.Forms.MessageBox.Show( ex.Message );

In the above code, the FillBy method is used for adding data from the Employee table of the
EmpDataSet.

Data Source Controls


ADO.NET's data source controls provide a declarative way to bind data from various sources
(like databases, XML files, or objects) to controls on your ASP.NET web forms. They simplify the
process of displaying, editing, and updating data, significantly reducing the amount of manual
code required compared to direct database interaction. They abstract away much of the
underlying data access plumbing, making development faster and easier.
Types of Data Source Controls:

The primary data source controls in ADO.NET are:

SqlDataSource: Connects to a SQL Server database. It allows you to specify connection strings,
SQL queries (SELECT, INSERT, UPDATE, DELETE), and parameter values. This is the most
commonly used data source control for SQL Server databases.

ObjectDataSource: Connects to business objects (classes) in your application. This is ideal for
working with data that isn't directly stored in a database, allowing you to connect controls to
your application logic layer.

AccessDataSource: Connects to a Microsoft Access database. Similar to SqlDataSource, but


specifically designed for Access.

XmlDataSource: Connects to XML data. Useful for binding data from XML files or streams.

SiteMapDataSource: Connects to the website's sitemap for navigation purposes. This isn't
directly a data source in the traditional sense, but it utilizes a data structure to render
navigation menus.

ADO.NET data source controls share these features:

Declarative Data Binding: You configure the data source through properties in your ASP.NET
page's design view or markup, rather than writing extensive code for database interaction.

Data Binding Expressions: Controls bound to a data source use expressions to access specific
fields from the data. For example, `<% Eval("ProductName") %>` displays the value of the
"ProductName" field.

Caching: Some data source controls offer caching capabilities to improve performance by
storing frequently accessed data in memory.

Parameterization: Protecting against SQL injection vulnerabilities is crucial. Data source controls
readily support parameterized queries, ensuring that user inputs are treated as data, not
executable code.

CRUD Operations (Create, Read, Update, Delete): Most data source controls allow you to
perform all four CRUD operations, simplifying data management. You define the SQL
commands (or methods for ObjectDataSource) for each operation.

Sorting, Paging, and Filtering: Many offer built-in support for sorting, paging, and filtering data,
allowing you to present data in a user-friendly manner.

Example (SqlDataSource):

Adding Data Source Controls using Visual Studio 2005


You can add SqlDataSource control by simply dragging control from Toolbox to a page. See
Figure 1.

Figure 1. SqlDataSource in Toolbox


When we drop SqlDataSource to a page,we will see Configure Data Source link. See Figure 2.

Figure 2. Configure Data Source


Clicking this link launches Configure Data Source wizard, which allows you to configure a data
source connection. See Figure 3. This wizard allows you to create a new connection or use
existing connections by selecting from data connection drop down list.
Figure 3. Configure Data Source wizard
Clicking New button of Configure Data Source wizard launches Connection Properties wizard,
which allows to create a new connection. See Figure 4.
Figure 4. Connection Properties wizard.
The next dialog of Configure Data Source wizard allows to specify the variable name of the
connection string. See Figure 5.
Figure 5. Connection string page
The following dialog allows you to specify the SELECT statement. Here you can select a
database table and its columns and add WHERE and ORDER BY clauses. See Figure 6.

Figure 6. Configure Select Statement dialog.


The next dialog tests the data. See Figure 7.

Figure 7. Test Query dialog.


Now this entire action adds the following code to the HTML file:

If we do not have Visual Studio, you can create SqlDataSource control in HTML by editing the
HTML code. As we can see from this code, tag <asp:SqlDataSource> represents the
SqlDataSource control and like other controls, we can set its parameters in HTML file. The
above code sets SelectCommand and ConnectionString parameters of SqlDataSource control.
We can also set the controls parameters from Properties window. As you can see from Figure 8,
we can set various properties of SqlDataSource including ConnectionString and SelectQuery.
Figure 8. SqlDataSource properties.

If InsertQuery property, it launches Command and Parameter Editor, where we can add and
remove parameters. See Figure 9. From this dialog, we can also launch Query Builder, which
allows you to create a SQL query.
Figure 9. Command and Parameter Editor

Formatting a GridView row


Formatting GridView rows in ADO.NET involves dynamically altering the appearance of
individual rows based on data values or other criteria. This can significantly enhance the user
experience by highlighting important information, drawing attention to errors, or simply
improving readability.

The GridView control is commonly used in ASP.NET applications to display and manipulate data
from a data source.

1.Understanding GridView:

A GridView is a versatile and powerful control that can display data in tabular format.
Each row within the GridView corresponds to a record from the data source, and each
column represents a field from that record.
2. Binding Data to GridView:

Before formatting can take place, data must first be bound to the GridView. This is
typically done using ADO.NET components such as `SqlConnection`, `SqlCommand`, and
`SqlDataAdapter`. Here’s a simplified example of how to bind data to a GridView:

C#

// Assuming you have a GridView control named GridView1


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}

private void BindGrid()


{
string connectionString = "your_connection_string";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand("SELECT FROM YourTable", connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
}
}

 Customizing Row Formatting:


The formatting of rows can be achieved in various ways:

a. Using the RowDataBound Event:


The `RowDataBound` event allows developers to customize the formatting of each row,
such as changing colors based on values, adding styles conditionally, or manipulating the
content dynamically.

C#
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Access data from the row
string status = e.Row.Cells[2].Text; // Assuming status is in the 3rd column (index 2)

// Apply conditional formatting


if (status == "Pending")
{
e.Row.BackColor = System.Drawing.Color.Yellow;
}
else if (status == "Completed")
{
e.Row.BackColor = System.Drawing.Color.LightGreen;
}
else if (status == "Error")
{
e.Row.BackColor = System.Drawing.Color.Red;
e.Row.ForeColor = System.Drawing.Color.White;
}

b. CSS Styling:
Using CSS is a strong way to style GridView rows. Assign
classes to rows or cells based on conditions, and define
our CSS styles in a separate stylesheet.

if (e.Row.RowIndex % 2 == 0)
{
e.Row.CssClass = "evenRow";
}
else
{
e.Row.CssClass = "oddRow";
}
// Accessing data using DataKeys
int id = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value);
// Use 'id' to perform further actions or fetch related data.
}
}
c. Template Fields:
TemplateFields provide greater control over the rendering of individual cells. You can add
controls like Labels, Images, or even custom user controls within the TemplateField and
manipulate their properties in the `RowDataBound` event. This allows for more complex
formatting and customization.

In the `RowDataBound` event:

C#
Label lblStatus = (Label)e.Row.FindControl("lblStatus");
if (lblStatus.Text == "Pending") { lblStatus.ForeColor = System.Drawing.Color.Blue; }

4. Using Alternating Row Styles (built-in):

The GridView's built-in `AlternatingRowStyle` property allows you to easily apply different
styles to alternate rows, providing a visual separation for better readability. This is
configured directly in the GridView's properties in the designer or through its properties in
your code-behind.

Selecting a GridView row


Selecting a GridView row in ADO.NET involves several steps and considerations, depending
on what you intend to do with the selected row. There's no single "select" method for a
GridView itself; it's a presentation control, not a data access component. The data behind
the GridView (usually a DataTable or DataSet populated from your database via ADO.NET) is
what you actually interact with.1. 1.Identifying the Row:

User Interaction (Client-Side): Typically, a user selects a row through a user interface
element like a checkbox within the GridView, or by clicking the row itself. This interaction
triggers a client-side event (e.g., `SelectedIndexChanged` in ASP.NET Web Forms, or similar
events in other UI frameworks). This event provides information about the selected row,
often through an index.
Programmatic Selection (Server-Side): You can programmatically select a row on the
server-side by identifying it through a unique identifier (like a primary key) from your data
source.
2. Data Binding with ADO.NET

Before you can select a row from a GridView, you first need to bind data to it. ADO.NET
provides the necessary components for connecting to a database, retrieving data, and
executing commands.

Example of Data Binding:

C#
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

public partial class MyPage : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}

private void BindGrid()


{
string connectionString = "your_connection_string_here";
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SELECT FROM MyTable", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
MyGridView.DataSource = dt;
MyGridView.DataBind();
}
}
}
```

In the above code:


- A connection to the database is established.
- A `SqlCommand` is executed to retrieve data.
- The data is filled into a `DataTable` and then bound to the `GridView`.

3. Accessing the Data:

Once you know which row is selected (either via user interaction or programmatically),
you need to access the data associated with that row. This involves:

Getting the Row Index: If the selection is based on user interaction, you'll have a row
index (e.g., `GridView1.SelectedIndex`).

Accessing the Data Source: The GridView's `DataSource` property holds the underlying
DataTable or DataSet.

Retrieving the Row Data: You can then use the row index to access the corresponding
DataRow in the DataTable:

C#
// Assuming 'gridView1' is your GridView and 'dt' is your DataTable
int rowIndex = gridView1.SelectedIndex;
if (rowIndex >= 0) {
DataRow selectedRow = dt.Rows[rowIndex];

// Access individual columns:


string columnName1 = selectedRow["ColumnName1"].ToString();
int columnName2 = Convert.ToInt32(selectedRow["ColumnName2"]);
// ... and so on
}
```

Using DataKeys: For better performance and reliability, especially with large datasets,
use the `DataKeyNames` property of the GridView. This property specifies which
column(s) in the DataTable serve as unique identifiers for each row. Then, you can
retrieve the DataRow directly using the key value:

C#
// Assuming DataKeyNames is set to "ID" in your GridView
int id = Convert.ToInt32(gridView1.SelectedDataKey.Value);
DataRow selectedRow = dt.Select("ID = " + id)[0]; //Finds the row based on ID
```

4. Handling the Selected Row:

After retrieving the data, you can perform various actions:

Update the data: Modify the values in the `selectedRow` and then update the
underlying database using ADO.NET commands (e.g., `SqlCommand` with `UPDATE`
statement).

Delete the data: Remove the `selectedRow` from the DataTable and then delete the
corresponding record in the database using ADO.NET commands (e.g., `SqlCommand`
with `DELETE` statement).

Display the data: Show the selected row's data in another control, like a details view or a
separate form.

Error Handling: Always include error handling (try-catch blocks) to manage exceptions,
such as `IndexOutOfRangeException` if the `SelectedIndex` is invalid.

Data Binding: Ensure your GridView is correctly bound to your data source.

Performance: For large datasets, avoid repeatedly accessing the data source. Consider
caching frequently accessed data. Using `DataKeyNames` significantly improves
performance over using `SelectedIndex`.

Security: Sanitize any user input used to select or manipulate rows to prevent SQL
injection vulnerabilities if you're directly constructing SQL queries. Use parameterized
queries instead.
Sorting and editing with the GridView
GridView: - The Asp.net GridView Control is successor control to the v1.x DataGrid Control.
With GridView control, you can display, edit, and delete data directly from different kinds of
data sources without writing any single piece of code.

GridView Control Features: -

1. Enhanced data source binding capabilities (Direct interaction with DataSource with any
writing any ADO.NET code)

2. Built-in support for sorting and paging functionalities

3. Improved Design time features (Smart Panel Tag)

4. Customized pager user interface with PagerTemplate property

5. Additional Column types (ImageField)

6. New Event model with support for pre-event and post-event operations

The GridView control in ASP.NET provides built-in support for sorting, editing, and deleting
data. Here is how you can implement these features:

Sorting:

 Set the GridView control’s AllowSorting property to true.

 Set the SortExpression property for each column that we want to be sortable.

 Handle the Sorting event of the GridView control and set the SortDirection property of
the event argument to Ascending or Descending, depending on the user’s selection.

Editing:

 Set the GridView control’s AutoGenerateEditButton property to true.

 Handle the RowEditing event of the GridView control to set the EditIndex property to
the index of the row being edited.

 Handle the RowCancelingEdit event of the GridView control to cancel the editing
operation.

 Handle the RowUpdating event of the GridView control to update the data in the
underlying data source.

Here is some sample code that demonstrates how to implement sorting and editing with the
GridView control:

<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False”


AllowSorting=”True” AutoGenerateEditButton=”True” AutoGenerateDeleteButton=”True”
OnSorting=”GridView1_Sorting” OnRowEditing=”GridView1_RowEditing”
OnRowCancelingEdit=”GridView1_RowCancelingEdit”
OnRowUpdating=”GridView1_RowUpdating” OnRowDeleting=”GridView1_RowDeleting”>

<Columns>

<asp:BoundField DataField=”ID” HeaderText=”ID” SortExpression=”ID” />

<asp:BoundField DataField=”Name” HeaderText=”Name” SortExpression=”Name” />

<asp:BoundField DataField=”Email” HeaderText=”Email” SortExpression=”Email” />

</Columns>

</asp:GridView>

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)

// Set the sort direction based on the current sort direction

if (e.SortDirection == SortDirection.Ascending)

e.SortDirection = SortDirection.Descending;

else

e.SortDirection = SortDirection.Ascending;

// Bind the data to the GridView control

BindData();

}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

// Set the edit index to the index of the row being edited

GridView1.EditIndex = e.NewEditIndex;

// Bind the data to the GridView control

BindData();

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

// Cancel the editing operation

GridView1.EditIndex = -1;

// Bind the data to the GridView control

BindData();

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

// Update the data in the underlying data source

// …

// Cancel the editing operation

GridView1.EditIndex = -1;

// Bind the data to the GridView control

BindData();

private void BindData()

// Bind the data to the GridView control


// …

GridView Paging
GridView is one of the most common tools for displaying data in a grid format in ASP.NET.
When the data becomes large, paging helps the users to view chunks of data and also increases
page load time. In this article, we will see how to implement paging in a GridView control.

the following steps to be followed will be used to make your ASP.NET GridView control with
paging enabled. The GridView control provides you with an easy way to display the number of
items on a page without taking up much space with the help of paging

1.we create an SQL Server database table.

2., insert data into the table.

3.drag the GridView control from the Data Controls menu. It will add the GridView control's
HTML source code as given above.

<asp:GridView ID="GridView2" runat="server">

</asp:GridView>

4.add the following namespace.

using System.Data.SqlClient;

using System.Data;

5.write the connection string to connect to the database.

string strConnection = "Data Source=.; uid=sa; pwd=wintellect; database=Rohatash;";

6.double-click on the page and write the following code for binding the data with the GridView.

protected void Page_Load(object sender, EventArgs e) {

BindData();

protected void BindData() {

string strConnection = "Data Source=.; uid=sa; pwd=wintellect;database=Rohatash;";

SqlConnection con = new SqlConnection(strConnection);

con.Open();
SqlCommand cmd = new SqlCommand("select * from Userinfo", con);

DataSet ds = new DataSet();

SqlDataAdapter da = new SqlDataAdapter(cmd);

da.Fill(ds);

GridView1.DataSource = ds;

GridView1.DataBind();

con.Close();

Implement PageIndexChanged

Once the event PageIndexChanging is executed, the event will be fired for PageIndexChanged
paging. In this event, you can safely bind the grid again to access the second page. It is always
preferable to cache the data used to bind the data source.

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) {

GridView1.PageIndex = e.NewPageIndex;

BindData();

There are four types of paging mode styles available in GridView. The following are the names
of the types of paging mode styles.

 NumericFirstLast

 Numeric

 NextPrevious

 NextPreviousFirstLast

Now click on the GridView control to load the control properties at the right-side panel; press
F4 and set the following properties of the GridView.

 Enable paging: EnablePaging property to True to get GridView Paging.

 PageSize: Number of rows from the data source to display per page.

 NumericFirstLast: Now, our GridView is ready with data, and I will explain how to use
each paging option in our GridView. If you look at the code above, I have set the
PagerSetting property for the GridView. Click on the GridView control, press F4, and set
the following properties.

<PagerSettings

Mode="NumericFirstLast"

PageButtonCount="4"

FirstPageText="First"

LastPageText="Last"

/>

 Mode: This is a display type of paging to use.

 PageButtonCount: To display a number of pages in the paging.

<PagerSettings

Mode="Numeric"

PageButtonCount="4"

/>

 FirstPageText: This will display text on the first page Button.

 LastPageText: This will display text on the last page Button.

 NextPrevious: If we want to use this mode for paging in GridView, we need to change
the PagerSettings mode to this.

<PagerSettings

Mode="NextPrevious"

NextPageText="Next"

PreviousPageText="Previous"

/>

 NextPageText: NextPageText property is used for the next page Button.

 PreviousPageText: PreviousPageText property is used for the next page Button

7.run the application


Crystal Report:-
To create a Crystal Report in ADO.NET C#, you need to: open Visual Studio, create a new
project, add a Crystal Report to your project, then use the Database Expert within Crystal
Reports to connect to your ADO.NET data source and design the report by selecting the desired
fields from your database tables; finally, write C# code to load and display the report in your
application.

Key steps:

1.Set up Project:

Open Visual Studio and create a new C# project (e.g., Windows Forms Application).

Add a reference to the Crystal Reports assembly if needed.

2.Create the Crystal Report:

Right-click on your project and select "Add New Item".

Choose "Crystal Reports" and give your report a name (e.g., "CustomerList.rpt").

Select "Blank Report" in the Crystal Report Gallery.

3.Connect to Data Source (Database Expert):

In the Crystal Report designer, go to "Database Expert".

Select your ADO.NET connection string.


Choose the tables and fields you want to display in your report from your database.

4.Design the Report:

Drag and drop fields from the Field Explorer onto the report design surface to create the layout.

Add sections (like Report Header, Details, Report Footer) as needed.

Format the report with fonts, colors, and styling.

5.Bind Data in C# Code:

In your C# code-behind file, create an instance of your report object.

Use an ADO.NET dataset to retrieve data from your database.

Set the "DataSource" property of your report to the dataset.

6.Display the Report:

Add a Crystal Report Viewer control to your form.

Set the "ReportSource" property of the viewer to your Crystal Report object.

Display the viewer on your form to show the generated report.

Example :-

// Create a dataset to hold data

DataSet ds = new DataSet();

// Fill the dataset with data from your database using ADO.NET commands

// ...

// Create a new instance of your Crystal Report

ReportDocument report = new ReportDocument();

report.Load("CustomerList.rpt"); // Load the Crystal Report file [1, 5, 6]

report.SetDataSource(ds.Tables[0]); // Set the data source [1, 4, 6]

// Display the report in a Crystal Report Viewer

CrystalReportViewer viewer = new CrystalReportViewer();

viewer.ReportSource = report;

this.Controls.Add(viewer);
Important Considerations:

 Data Connection:

Ensure your ADO.NET connection string is correctly configured to access your


database.

 Security:

If you are deploying your application, consider security measures to manage


access to the Crystal Reports data source.

 Customization:

Explore advanced features of Crystal Reports like parameters, grouping, and


formulas to tailor your reports.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy