0% found this document useful (0 votes)
11 views104 pages

Module 7

The document provides an overview of ADO.NET, a framework for data access in .NET applications, detailing its components such as the .NET Framework data providers and DataSet. It explains how to connect to SQL Server databases using the System.Data.SqlClient namespace, create connections, and execute commands. Additionally, it covers the architecture of ADO.NET, including connected and disconnected models, and the use of DataReaders and DataAdapters for data manipulation.

Uploaded by

PAulos
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)
11 views104 pages

Module 7

The document provides an overview of ADO.NET, a framework for data access in .NET applications, detailing its components such as the .NET Framework data providers and DataSet. It explains how to connect to SQL Server databases using the System.Data.SqlClient namespace, create connections, and execute commands. Additionally, it covers the architecture of ADO.NET, including connected and disconnected models, and the use of DataReaders and DataAdapters for data manipulation.

Uploaded by

PAulos
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

Department of CE/IT

Dot Net Technologies

Playing with data using [Link] Unit no : 7


Dot Net Technologies
(01CE0602)
Unit 7: Playing with data using [Link]
1) Overview of [Link] Framework Department of CE/IT
2) working with SQLserver database
3) Managed Provider, Dataset Unit no : 7
4) working with data source Dot Net Technology
(01CE0602)
5) Connected and disconnected architecture
6) Binding data with Datagrid
7)Binding data with Crystal Report
To work with database you need
[Link] namespace.

to add above name space, right click on


project solution copy and select manage
Nuget packages for solution

Database
Connectivity
Click on Browse and type “[Link]” and press enter.

Database
Connectivity
Click on install

Database
Connectivity
Click on ok

Database
Connectivity
Click on “I Accept”

Database
Connectivity
On Installation it will show as shown here:

Database
Connectivity
Now we have the namespace “[Link]” added to our
application

Now to create a database

Database  Click in server Explorer, if not visible click on view menu

Connectivity
Database
Connectivity Right click on Data Connections
Select Create new SQL Server Database

Database
Connectivity
Put server name as “(localdb)\MSSQLLOCALDB”

 and new database name as you want, here it is Emp

Click on ok
Database
Connectivity
A database will be created

Database
Connectivity
If you have database, already created, for e.g we want to connect again
to Emp database, which we have created above.

Database
Connectivity
Right click on Data Connections
Click on Add Connections

Database
Connectivity
Click on Continue

Database
Connectivity
Put server name as
(localdb)\MSSQLLOCALDB

Select Emp

Database Click on test Connection

Connectivity

Click on ok
[Link] is a set of classes that expose data access services for .NET
Framework programmers.

 It is an integral part of the .NET Framework, providing access to


relational, XML, and application data.

[Link] is a set of classes (a framework) to interact with data


[Link] sources such as databases and XML files.
 ADO is the acronym for ActiveX Data Objects. It allows us to
connect to underlying data or databases.

It has classes and methods to retrieve and manipulate data.

The [Link] classes are found in [Link], and are


integrated with the XML classes found in [Link].
[Link] provides consistent access to data sources such as SQL
Server and XML, and to data sources exposed through OLE DB and
ODBC.
Data-sharing consumer applications can use [Link] to connect to
these data sources and retrieve, handle, and update the data that they
contain.
[Link] separates data access from data manipulation into discrete
[Link] components that can be used separately or in tandem (in combination) .
[Link] includes .NET Framework data providers for connecting to
Overview a database, executing commands, and retrieving results.
Those results are either processed directly using DataReader, or placed
in an [Link] DataSet object in order to be exposed to the user in an
ad hoc manner, combined with data from multiple sources, or passed
between tiers.
[Link] has two main components that are used for accessing and
manipulating data are the .NET Framework data provider and the
DataSet.
Data processing has traditionally relied primarily on a connection-based,
two-tier model.

As data processing increasingly uses multi-tier architectures, programmers


are switching to a disconnected approach to provide better scalability for
their applications.

[Link]
Architecture The two main components of [Link] for accessing and manipulating
data are the .NET Framework data providers and the DataSet.
The .NET Framework Data Providers are components that have been
explicitly designed for data manipulation and fast, forward-only, read-only
access to data.
The Connection object provides connectivity to a data source.
The Command object enables access to database commands to return data,
.NET modify data, run stored procedures, and send or retrieve parameter

Framework
information.
The DataReader provides a high-performance stream of data from the data
Data source.

Providers Finally, the DataAdapter provides the bridge between the DataSet object
and the data source.
The DataAdapter uses Command objects to execute SQL commands at the
data source to both load the DataSet with data and reconcile changes that
were made to the data in the DataSet back to the data source.
A .NET Framework data provider is used for connecting to a database,
executing commands, and retrieving results.
Those results are either processed directly, placed in a DataSet in order to
be exposed to the user as needed, combined with data from multiple
sources, or remoted between tiers. .
.NET NET Framework data providers are lightweight, creating a minimal layer

Framework
between the data source and code, increasing performance without
sacrificing functionality.
Data
Providers
.NET Framework data provider - Description.
NET Framework Data Provider for SQL - ServerProvides data access for
Microsoft SQL Server. Uses the [Link] namespace.

.NET .NET Framework Data Provider for OLE DB - For data sources exposed by
using OLE DB. Uses the [Link] namespace.
Framework
Data .NET Framework Data Provider for ODBC - For data sources exposed by
Providers using ODBC. Uses the [Link] namespace.

.NET Framework Data Provider for Oracle - For Oracle data sources. The
.NET Framework Data Provider for Oracle supports Oracle client software
version 8.1.7 and later, and uses the [Link] namespace
The 4 core objects that make up a .NET Framework data provider.
1. Connection - Establishes a connection to a specific data source. The base
class for all Connection objects is the DbConnection class.
2. Command - Executes a command against a data source.
Core Objects Exposes Parameters and can execute in the scope of a Transaction from
a Connection. The base class for all Command objects is
of .NET the DbCommand class.
Framework 3. DataReader - Reads a forward-only, read-only stream of data from a data
source. The base class for all DataReader objects is
Data the DbDataReader class.
Providers 4. DataAdapter - Populates a DataSet and resolves updates with the data
source. The base class for all DataAdapter objects is
the DbDataAdapter class.
The [Link] DataSet is explicitly designed for data access independent
of any data source.

As a result, it can be used with multiple and differing data sources, used
with XML data, or used to manage data local to the application.

DataSet  The DataSet contains a collection of one or more DataTable objects.

DataTable objects consisting of rows and columns of data, and also primary
key, foreign key, constraint, and relation information about the data in
the DataTable object.
The following diagram illustrates the relationship between a .NET
Framework data provider and a DataSet.

DataSet

DataSet Object Model


Use a DataSet to do the following:
1. Cache data locally in your application so that you can manipulate it. If
you only need to read the results of a query, the DataReader is the better
choice.
2. Remote data between tiers or from an XML Web service.
3. Interact with data dynamically such as binding to a Windows Forms
control or combining and relating data from multiple sources.
4. Perform extensive processing on data without requiring an open
DataSet connection to the data source, which frees the connection to be used by
other clients.
If you do not require the functionality provided by the DataSet, you can
improve the performance of your application by using the DataReader to
return your data in a forward-only, read-only manner.
Although the DataAdapter uses the DataReader to fill the contents of
a DataSet by using the DataReader,.
As you can boost performance because you will save memory that would
be consumed by the DataSet, and avoid the processing that is required to
create and fill the contents of the DataSet.
Managed provider is a term used for a group of .NET components that
implement a fixed set of functionality set forth by the [Link]
architecture.

This enforces a common interface for accessing data.

Managed Microsoft provides two managed providers in its current release of


[Link]: OLE DB and SQL.
Povider
The OLE DB managed provider comes with OleDbConnection,
OleDbCommand, OleDbParameter, and OleDbDataReader.

The SQL Server managed provider comes with a similar set of objects,
whose names start with SqlClient instead of OleDb
The implementation of this core function set for managed providers is
packaged in the [Link] namespace, while the interfaces for
the data adapter classes are in [Link].

The Managed Providers have four core components:


1. Connection—The Connection represents a unique session to a data store.
This may be manifested as a network connection in a client/server database
application.
Managed 2. Command—The Command represents a SQL statement to be executed on
Provider 3.
a data store.
DataReader—The DataReader is a forward-only, read-only stream of data
records from a data store to a client.
4. DataAdapter—The DataAdapter represents a set of Commands and a
Connection which are used to retrieve data from a data store and fill a
DataSet.
✓ Now we will be looking at a four components from [Link]
name space.
The SqlConnection Object takes connection string as its argument, while
creating instance.
Connection string consisit of atleast 3 parameters:
1. Data Source – name of the server to connect
2. Initial catalog - name of the database to connect
3. Integrated Security – true. If windows authentication is used, else false.
Sql ✓ All parameters of connection string are separated by semi-colon (“;”)

Connection ✓ Example: string cs=@”Data Source = (localdb)\MSSQLLOCALDB;


Initial Catalog = Emp; Integrated Security = true”;
✓ The string is preceded with “@”, to treat string as raw string.
✓ In case of Sql Authentication , instead of windows authentcation, add 2
more parameters as part of connection string
1. User ID – user name for authentication
2. Password – password for authentication
Creating SqlConnection Instance:
Example:
string cs=@”Data Source = (localdb)\MSSQLLOCALDB; Initial Catalog = Emp;
Integrated Security = true”;
SqlConnection conn=new SqlConnection(cs);
Once we create the instance (object) of SqlConnection, we can call methods of
class, connecting to the database and disconnecting from database
Open() - used to open connection
Close() – Closes the Connection that was Opened
Sql To ensure Connection is always closed, after opening, to do that automatically
Connection use Using…..Block
Example:
using (SqlConnection connection = new SqlConnection(cs))
{
[Link]();
// Do work here; connection closed on following line.
}
Properties:
1. Database - Gets the name of the current database or the database to be
used after a connection is opened.
2. DataSource - Gets the name of the instance of SQL Server to which to
connect.
3. ServerVersion - Gets a string that contains the version of the instance of
SQL Server to which the client is connected.

Sql 4. ConnectionString - Gets or sets the string used to open a SQL Server
database.
Connection
Methods:
1. ChangeDatabase() - Changes the current database for an
open SqlConnection.
2. Open()- Opens a database connection with the property settings specified
by the ConnectionString.
3. Close() - Closes the connection to the database. This is the preferred
method of closing any open connection.

Sql 4. CreateCommand() - Creates and returns a SqlCommand object


associated with the SqlConnection.
Connection
SqlCommand object is one that will be running the query against the
database, thus while creating SqlCommand Object, we provide the Query
and ConnectionOject
Query - the SQL statement that need to be run against database
ConnectionObject – instance of SqlConnection that we created to connect
to the database
Example:

Sql string cs=@”Data Source = (localdb)\MSSQLLOCALDB; Initial Catalog =


Emp; Integrated Security = true”;
Command string query = @”select empid,empname from empData;”;
using (SqlConnection connection = new SqlConnection(cs))
{
[Link]();
SqlCommand cmd=new SqlCommand(query,conn);
}
Once we have SqlCommand Instance ready, we can run the given
query (such as CREATE, UPDATE, INSERT, or DELETE)against the
database, by using the methods of SqlCommand Class using its instance.
Methods:
1. ExecuteNonQuery() - Executes a Transact-SQL statement against the
connection and returns the number of rows affected.
2. ExecuteReader() - Sends the CommandText to the Connection and
Sql builds a SqlDataReader.

Command 3. ExecuteScalar() - Executes the query, and returns the first column of the
first row in the result set returned by the query. Additional columns or
rows are ignored.
Properties:
1. Connection - Gets or sets the SqlConnection used by this instance of
the SqlCommand.
2. CommandTimeout - Gets or sets the wait time (in seconds) before
terminating the attempt to execute a command and generating an error.
3. CommandType - Gets or sets a value indicating how the CommandText
property is to be interpreted. The default is Text.
Sql 4. CommandText - Gets or sets the Transact-SQL statement, table name or
Command stored procedure to execute at the data source. The default is empty string.
Provides a way of reading a forward-only stream of rows from a SQL
Server database.
On running the ExecuteReader() method of SqlCommand Object, a
instance of DataReader is returned.
We can refer that returned instance with reference of SqlDataReader.
Lets look the example reads through the data, writing it out to the console
window.
Sql
DataReader
using System;
using [Link];
using [Link];
class Program {
static void Main() {
string str = "Data Source=(localdb)\MSSQLLOCALDB;Initial Catalog=Emp;"
Sql + "Integrated Security=true";

DataReader ReadOrderData(str);
}
private static void ReadOrderData(string cs) {
string query= @"SELECT empid,empname FROM empData;";
using (SqlConnection connection = new SqlConnection(cs))
{ SqlCommand command = new SqlCommand(query, connection);
[Link]();
SqlDataReader reader = [Link]();
Sql // Call Read before accessing data.
DataReader while ([Link]()) {
[Link](reader[0]+” “+ reader[1]);
}
[Link](); // Call Close when done reading.
} }}
Properties:
1. Connection - Gets the SqlConnection associated with the SqlDataReader.
2. FieldCount - Gets the number of columns in the current row.
3. HasRows - Gets a value that indicates whether the SqlDataReader
contains one or more rows.
4. IsClosed - Retrieves a Boolean value that indicates whether the
Sql specified SqlDataReader instance has been closed.

DataReader
Methods:
1. GetByte() - Gets the value of the specified column as a byte.
2. GetChar() - Gets the value of the specified column as a single character.
3. GetDouble Gets the value of the specified column as a double-precision
floating point number.
4. GetFloat() - Gets the value of the specified column as a single-precision
Sql 5.
floating point number.
GetValue() - Gets the value of the specified column in its native format.
DataReader
Represents a set of data commands and a database connection that are used
to fill the DataSet and update a SQL Server database.
This class cannot be inherited.
The SqlDataAdapter, serves as a bridge between a DataSet and SQL Server
for retrieving and saving data.
The SqlDataAdapter provides this bridge by mapping :

Sql 1. Fill, which changes the data in the DataSet to match the data in the data
source, and
DataAdapter 2. Update, which changes the data in the data source to match the data in
the DataSet, using the appropriate Transact-SQL statements against the
data source. The update is performed on a by-row basis.
Lets initializes a new instance of the SqlDataAdapter class.
Constructor’s:
1. SqlDataAdapter() - Initializes a new instance of
the SqlDataAdapter class.
2. SqlDataAdapter(SqlCommand) - Initializes a new instance of
the SqlDataAdapter class with the specified SqlCommand as
the SelectCommand property.
Sql 3. SqlDataAdapter(String, SqlConnection) - Initializes a new instance of
DataAdapter the SqlDataAdapter class with a SelectCommand and
a SqlConnection object.
4. SqlDataAdapter(String, String) - Initializes a new instance of
the SqlDataAdapter class with a SelectCommand and a connection
string.
Example:
string cs=@”Data Source = (localdb)\MSSQLLOCALDB; Initial Catalog =
Emp; Integrated Security = true”;
string query = @”select empid,empname from empData;”;
using (SqlConnection connection = new SqlConnection(cs))
{
Sql [Link]();

DataAdapter SqlDataAdapter da=new SqlDataAdapter(query, connection);


//remaining code ahead
}
Properties:
1. DeleteCommand - Gets or sets a Transact-SQL statement or stored
procedure to delete records from the data set.
2. InsertCommand - Gets or sets a Transact-SQL statement or stored
procedure to insert new records into the data source.
3. SelectCommand - Gets or sets a Transact-SQL statement or stored
procedure used to select records in the data source.
Sql 4. UpdateCommad - Gets or sets a Transact-SQL statement or stored
DataAdapter procedure used to update records in the data source.
Methods:
1. Fill(DataSet) - Adds or refreshes rows in the DataSet. (Inherited
from DbDataAdapter)
2. Fill(DataTable) - Adds or refreshes rows in a specified range in
the DataSet to match those in the data source using the DataTable name.
(Inherited from DbDataAdapter)
3. Fill(DataSet, String) - Adds or refreshes rows in the DataSet to match
Sql those in the data source using the DataSet and DataTable names.

DataAdapter 4. Dispose() - Dispose()Releases all resources used by the Component.


Dataset

DataTable DataRelation
Collection Collection

Dataset DataTable DataRelation

DataRow Data
Collection ColumnCollection

DataRow DataColumn
Represents one table of in-memory data.
Following example creates an instance of a DataTable object and assigns it
the name “Emp“
DataTable workTable = new DataTable(“Emp");

Dataset is collection of such table, to add table to a dataset, or creates an


instance of a DataTable by adding it to the Tables collection of a DataSet.
DataTable DataSet customers= new DataSet();
DataTable customersTable = [Link](“cutomer_details");


A DataTable contains a collection of DataColumn objects referenced by
the Columns property of the table.
This collection of columns, along with any constraints, defines the schema, or
structure, of the table.
You create DataColumn objects within a table by using the DataColumn
constructor, or by calling the Add method of the Columns property of the
table, which is a DataColumnCollection.
The Add method accepts optional ColumnName, DataType, and Expression
DataTable arguments and creates a new DataColumn as a member of the collection.
It also accepts an existing DataColumn object and adds it to the collection,
and returns a reference to the added DataColumn if requested.
 Because DataTable objects are not specific to any data source, .NET
Framework types are used when specifying the data type of a DataColumn.
Example: Adding 3 Columns to DataTable
DataTable workTable = new DataTable(“Emp");
DataColumn workCol = [Link](“EmpID", typeof(Int32));
[Link] = false;
[Link] = true;
[Link](“EmpName", typeof(String));

DataTable [Link](“Contact", typeof(String));


Lets create a form, to collect the EmpID, EmpName and Contact.
Once the user fills the below form on Clicking Ok, the record should be
should be added to DataTable, to verify the addition f record, label is added to
display the number of records in table.

DataTable
Example
DataTable
Example
Add Checkbox to previous Form, which enable, to visit and display the
records of DataTable.

Activity
Add the following code to existing code, to display records using Previous
and Next button in [Link] file.

Activity
To display Previous and Next, on the state of checkbox, add the following
code to existing code, in [Link] file.

Activity
Till now we have created DataTable Manually by extracting data from
compnents of form.

Lets add the data to the DataTable from the Data Source.

To fill the DataTable from DataSource we need DataAdapter Object


working with
data source Lets look at an Example
We have table Emp with given schema.
We will be extracting empid, name , sal from below table schema to display
on form
We will fill the DataTable using DataAdapter, with informtion availabale in
table shown below.
Let start with example

working with
data source
Given form to be Loaded.

working with
data source
As soon as you click Load, the data from employee table shown before, will
be added consisting of columns emp_id, name, sal only.

working with
data source
working with
data source
working with
data source
Now if you have more than one table to be loaded , you create Dataset and
load it from DataSource.
Lets say we have products table as shown below:

working with
data source
And we have Emp table as shown before

working with
data source
Now lets load a Form with data from both the tables using data set.

working with
data source
Now lets load a Form with data from both the tables using data set.

working with
data source
working with
data source
working with
data source
[Link] supports two different programming environments: connected and
disconnected.

Connected
and
[Link]
disconnected
architecture
Connected Disconnected
The connected environment provides forward-only, read-only access to data
in the data source and the ability to execute commands against the data
source.

The connected classes provide a common way to work with connected data
regardless of the underlying data source.

Connected Includes Connection, Command, DataReader, Transaction, ParameterColle


ction, and Parameter classes.
The disconnected environment allows data retrieved from the data source to
be manipulated and later reconciled with the data source.

The disconnected classes provide a common way to work with disconnected


data regardless of the underlying data source.

They include the DataSet, DataTable, DataColumn, DataRow, Constraint,


Disconnected DataRelationship, and DataView classes.
Finally, [Link] introduces the connected DataAdapter class to bridge the
data source and disconnected classes by way of the connected classes.

The DataAdapter is an abstraction of the connected classes that simplifies


filling the disconnected DataSet or DataTable classes with data from the data
source and updating the data source to reflect any changes made to the
disconnected data.

Disconnected Figure in next slide shows the relationship between the connected and
disconnected classes in [Link].
Relationship
Between
Connected &
Disconnected
Architecture

Figure - The connected and disconnected [Link] classes


The following classes are used by [Link] to communicate directly with
the data source:
Connection:
➢Maintains information required to connect to the data source through a
connection string.
➢The connection string contains information such as the name of the data
source and its location, and authorization credentials and settings.
Connected ➢The Connection class has methods to open and close the connection, for
Classes transactions to be initiated on the connection, as well as control other
properties of the connection.
Command:
➢Executes SQL statements or stored procedures against the data source.
➢The command class has a ParameterCollection object
containing Parameter objects that allow parameterized SQL statements and
stored procedures to be used against the data source.
DataReader:
➢Provides connected forward-only, read-only access to the data source.
➢It is optimized for speed.
➢The DataReader is instantiated through a Command object.
Parameter:
➢Allows parameters for both parameterized queries and stored procedures to be
Connected defined and set to appropriate values.

Classes ➢The Parameter class is accessed through the ParametersCollection object


within a Command object.
➢It supports input and output parameters as well as return values from stored
procedures.
✓Transaction:
➢Allows transactions to be created on a connection so that multiple changes to
data in a data source are treated as a single unit of work and either all
committed or cancelled.
DataAdapter
Bridges the data source and the disconnected DataSet or DataTable classes.
 The DataAdapter wraps the connected classes to provide this functionality.
It provides a method to retrieve data into a disconnected object .
Also a method to reconcile modified data in the disconnected object with the
data source.
Connected
Classes
The following [Link] classes allow data to be retrieved from the data set,
examined and modified offline, and reconciled with the data source through
the DataAdapter:
DataSet:
➢Provides a consistent way to deal with disconnected data completely
independently of the data source.
➢The DataSet is essentially an in-memory relational database, serving as a
container for the DataTable, DataColumn, DataRow, Constraint,
and DataRelation objects.
Disconnected ➢The XML format serializes and transports a DataSet.
Classes ➢A DataSet can be accessed and manipulated either as XML or through the
methods and properties of the DataSet interchangeably;
➢ the XmlDataDocument class represents and synchronizes the relational data
within a DataSet object with the XML Document Object Model (DOM).
DataTable
➢Allows disconnected data to be examined and modified through a collection
of DataColumn and DataRow classes.
➢The DataTable allows constraints such as foreign keys and unique constraints
to be defined using the Constraint class.
DataColumn:
Corresponds to a column in a table.
The DataColumn class stores metadata about the structure of the column that,
together with constraints, defines the schema of the table.
The DataColumn can also create expression columns based on other columns in
the table.
DataRow:

Disconnected ➢Corresponds to a row in a table and can examine and update data in the DataTable.
➢ The DataTable exposes DataRow objects through the DataRowCollection object
Classes it contains.
➢The DataRow caches changes made to data contained in its columns, storing both
original and current values.
➢This allows changes to be cancelled or to be later reconciled with the data source.
Constraint:
➢Allows constraints to be placed on data stored within a DataTable.
➢Unique and foreign key constraints can be created to maintain data integrity.
DataRelation:
➢Provides a way to indicate a relationship between different DataTable objects
within a DataSet.
➢The DataRelation relates columns in the parent and child tables allowing
navigation between the parent and child tables and referential integrity to be
enforced through cascading updates and deletes.
DataView:
Disconnected ➢Allows data, once retrieved into a DataSet or DataTable, to be viewed in
Classes different ways.
➢It allows data to be sorted based on column values and for a subset of the data
to be filtered so that only rows matching specified criteria are displayed.
Difference between Connected and Disconnected Architecture

Connected Disconnected

It is connection oriented. It is dis_connection oriented.

Connected methods gives faster Disconnected get low in speed and


performance performance.

To retrieve data use, DataReader Retrieval of data is from DataSet


Comparison Connected architecture can hold the Disconnected architecture can hold data
data of single table of multiple tables

Connected you need to use a read only In Disconnected you cannot use.
forward only data reader

Data Reader can’t persist the data DataSet can persist the data

It is Read only, we can’t update the data. Data can be updated


The DataGridView control provides a powerful and flexible way to display
data in a tabular format.

You can use the DataGridView control to show read-only views of a small
amount of data, or you can scale it to show editable views of very large sets of
data
.

DataGridView With the DataGridView control, you can display and edit tabular data from
many different kinds of data sources
.
Binding data to the DataGridView control is straightforward and intuitive, and
in many cases it is as simple as setting the DataSource property.

When you bind to a data source that contains multiple lists or tables, set
the DataMember property to a string that specifies the list or table to bind to.
The DataGridView control is highly configurable and extensible, and it
provides many properties, methods, and events to customize its appearance
and behavior.

When you want your Windows Forms application to display tabular data,
consider using the DataGridView control before others (for
example, DataGrid).

DataGridView If you are displaying a small grid of read-only values, or if you are enabling a
user to edit a table with millions of records, the DataGridView control will
provide you with a readily programmable, memory-efficient solution.
In a toolbox search box type DataGridView to locate component in toolbox

DataGridView

Drag and Drop Component on the Form


DataGridView
DataGridView

You can click on small arrow over the DataGridView component


DataGridView

DataGridview displays tabular data, you can specify the table format
manually by adding columns or you can assign DataSource from where this
component will be loaded with tabular information.
Specifying the table information to be displayed Manually
Click on Add Columns

DataGridView
It will display the window as shown below:

DataGridView
Lets add 2 columns RollNo and Name
Adding Coloumn 1-Roll No, provide details of columns and click on Add.

DataGridView
Similarly Add Coloumn 2-First Name, provide details of columns and click
on Add, then click on Close.

DataGridView
Similarly Add Coloumn 2-First Name, provide details of columns and click
on Add, then click on Close.
After applying above steps the datagridview looks as shown below

DataGridView
Now lets add, 2 TextBox for taking roll number and name as input, and
adding the information in DataGridView on clicking Add button

DataGridView
Now lets add, 2 TextBox for taking roll number and name as input, and
adding the information in DataGridView on clicking Add button

DataGridView
Now lets add, 2 TextBox for taking roll number and name as input, and
adding the information in DataGridView on clicking Add button

DataGridView
DataGridView
DataGridView
DataGridView
Specifying the DataSource for DataGridview to display the tabular data
directly without adding columns.
The DataSource is DataTable, however you can set DataSource to Dataset but
in that case you need to set the DisplayMember.
Lets go Through Example.
A Form is there with DataGridView as shown below:

DataGridView
To load this DataGridView with information from data source, using DataSet

DataGridView
DataGridView
DataGridView data source is DataTable, to the previous form we add button
named “Load DataTable”, on clicking it will add the content of DataTable for
display in DataGridView.

DataGridView
Add the following code in the existing code shown for form9 before

DataGridView

Now run program and click on Load DataTable button..


DataGridView
Thanks
Form9 – DataGridView with DataSource
Form8 – DataGridView Manual Filling
Form7 - Adding Data to DataTable and displaying , each row
with next and prev button
Form6 - Load DataTable from DataSource i.e from Database
Form5 – Loads Dataset from DataSource
Form4 – Loads the form control with row from datatable, to
display records 1 by 1.
Form3 – creates and loads DataTable programmatically
Form2 –Traverse each of row of DataTable –Activity to be
done by students
Form 1 - Loads DataTable from Database, shows Update
demo, to reflect change in DataTable back to Database

You might also like