UNit 5 ADO.NET
UNit 5 ADO.NET
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.
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 :
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.
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
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
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:
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:
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:
C#
```
Once you have your connection string, you use ADO.NET classes to connect, execute
commands, and process results. Common classes include:
Transactions: For ensuring data integrity by grouping multiple operations into a single
atomic unit.
connection.Open();
while (reader.Read())
Console.WriteLine(reader["ColumnName"]);
```
DataReaders: Efficient for reading data sequentially, suitable for reporting or displaying
lists.
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.
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.
`ExecuteNonQuery()` for INSERT, UPDATE, and DELETE statements, returning the number of affected
rows.
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.
using System.Data.SqlClient;
try
connection.Open();
while (reader.Read())
connection.Close();
``
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.
Open a connection
Work with the DataSet (e.g., display and edit in a user interface) - this may take longer
Synchronize changes
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#
adapter.Fill(dataSet, "Users");
usersTable.Rows.Add(newRow);
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
```
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.
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.
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.
Select Command.
Insert Command.
Update Command.
Delete Command.
When we call the Fill() method of Adapter, the following action takes place internally.
Execute the Select command under it on the DataSource and loads data from the table to the
DataSet.
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:
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.
4. DataTable:
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:
Establish a connection to the database using a SqlConnection and use a DataAdapter to fetch
data from the database and populate a DataSet.
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#
dataAdapter.Fill(dataSet, "Employees");
...
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
conn.Open();
string query = "SELECT ID, Name, Age FROM Employees"; // Fetch data from
DB
SqlDataAdapter adapter = new SqlDataAdapter(query, conn);
// Apply Sorting
}
// Proving disconnection: Modify DataView without any DB connection
newRow["ID"] = 999;
newRow["Age"] = 35;
newRow.EndEdit();
Improved Performance: Reduces the load on the database server, particularly in situations with
many concurrent users or large datasets.
Data Integrity: Provides a mechanism for managing transactions and ensuring data consistency
through the `Update()` method.
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.
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.
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.
Bind all the other text boxes with the database values.
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.
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
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
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 Text property and click on the drop down list.
1Expand the Other Data Sources, Project Data, Sources, Orderdataset, Orderdata nodes.
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
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:
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:
con.Open();
string studid;
studid = textbox1.Text;
SqlDataReader dr = cmd.ExecuteReader();
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.
Code:
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
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:
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.
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.
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.
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):
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
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#
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)
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.
C#
Label lblStatus = (Label)e.Row.FindControl("lblStatus");
if (lblStatus.Text == "Pending") { lblStatus.ForeColor = System.Drawing.Color.Blue; }
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.
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.
C#
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
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];
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
```
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.
1. Enhanced data source binding capabilities (Direct interaction with DataSource with any
writing any ADO.NET code)
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 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:
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:
<Columns>
</Columns>
</asp:GridView>
if (e.SortDirection == SortDirection.Ascending)
e.SortDirection = SortDirection.Descending;
else
e.SortDirection = SortDirection.Ascending;
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;
BindData();
GridView1.EditIndex = -1;
BindData();
// …
GridView1.EditIndex = -1;
BindData();
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
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>
using System.Data.SqlClient;
using System.Data;
6.double-click on the page and write the following code for binding the data with the GridView.
BindData();
con.Open();
SqlCommand cmd = new SqlCommand("select * from Userinfo", con);
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.
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.
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"
/>
<PagerSettings
Mode="Numeric"
PageButtonCount="4"
/>
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"
/>
Key steps:
1.Set up Project:
Open Visual Studio and create a new C# project (e.g., Windows Forms Application).
Choose "Crystal Reports" and give your report a name (e.g., "CustomerList.rpt").
Drag and drop fields from the Field Explorer onto the report design surface to create the layout.
Set the "ReportSource" property of the viewer to your Crystal Report object.
Example :-
// Fill the dataset with data from your database using ADO.NET commands
// ...
viewer.ReportSource = report;
this.Controls.Add(viewer);
Important Considerations:
Data Connection:
Security:
Customization: