You are on page 1of 12

In-Depth look at the GridView Control

Introduction:

In the last article we looked at few of the new controls available in Asp.net 2.0. We also talked
about Grid View Control which has replaced the Asp.net 1.1 DataGrid control for good. In this
article we will examine more features of the Grid View control. In this article we will see some of
the common operations that can be performed using the GridView control. Apart from these
operations there are many more functions that can be performed on the control and which we will
see in the later articles.

Adding a SqlDataSource and binding to GridView Control:

In this article I will be using the Northwind database which comes with SQL Server 2000. In the
last article I explained how easy it is to bind the Grid View control to the SqlDataSource. You can
perform all these actions using the wizard. If you want to code and bind the datasource you can
easily perform it using the following code sample:

void Page_Load(object sender, EventArgs e)


{

if (!Page.IsPostBack)
{

// Binds the data

BindData();

public void BindData()


{

// you can use this line

string connectionString = myDataSource.ConnectionString;

// you can also use this line since by using the SqlDataSource it makes an entry in the
// web.config file if that is what choose to do
//string connectionString = (string)ConfigurationSettings.AppSettings["ConnectionString"];
// if you are using Enterprise Library you can also use
//string connectionString =
(string)ConfigurationSettings.ConnectionStrings["ConnectionString"];

SqlConnection myConnection = new SqlConnection(connectionString);

SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories", myConnection);

DataSet ds = new DataSet();


ad.Fill(ds, "Categories");

myGridView.DataSource = ds;

myGridView.DataBind();

You will need to set the Bound column in order to see the text in the cells of the grid view control.
This can be easily done by using the Smart tag which appears when you right click on the grid
view control.

I have also added a Status column to show you the checkbox column feature. The Status column
is a simple bit field whose value can be either 1 or 0. If you are using Access database you can
choose Yes/No Column. Once you have set up all your columns and execute the page it will
display something like this:

At this moment if you try to select the Checkbox column, meaning if you try to check or uncheck
the Status column it won't work. Let's see how we can make it work with our grid view control.
In the above image you see that the Checkboxes are not marked. The reason is because in the
database the Checkbox column is NULL. If you make the column value to either 1 or 0 you will
see check marks where the value is 1. See the image below and you will have a better idea of
what I mean.

Editing in the Grid View Control

You can easily add the editing, updating, selecting, paging and sorting capabilities to your grid
view control. Just add a new command column and you will be asked to add whatever
functionality you desire.

If you are using the SqlDataSource to bind to the GridView control you will get most of the
features by just using the SqlDataSource wizard. Since we are binding the control at runtime we
need to add most of the functionality manually.

Edit Mode:

The fields that are marked readonly = false will change into TextBoxes when the Row_Editing
event triggers. Like DataGrid control its easy to set the fields in the edit mode.

// Editing mode

void myGridView_RowEditing(object sender, GridViewEditEventArgs e)


{

myGridView.EditIndex = e.NewEditIndex;

BindData();

Cancel Edit:

If you don't like to edit the row you can press cancel link button which will fire the
RowCancelingEdit event. The code to turn the row back to its original form is quite simple and
straight forward.

// Cancel Edit Mode

void myGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)


{
myGridView.EditIndex = -1;

BindData();

Selecting Row:

Selecting row event is fired when you make a click on the select link. If you need any particular
item in that row you can easily select it using the cells property:

// Selecting row

void myGridView_SelectedIndexChanged(object sender, EventArgs e)


{

// This will contain the selectedValue of the row

string selectedCategory = myGridView.SelectedRow.Cells[1].Text;

The Cells start with index '0' which means Cell[0] is CategoryID , Cell[1] is CategoryName and so
on.

Update Row:

For Updating the row we first need to get the value from the row that is entered by the user into
the TextBox. For this purpose you can change the bound column into a Template column which
will make is easier to locate the item.

After changing the CategoryName column to a tem plated column we can easily use the
RowUpdating event to find the Text entered by the user.

void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)


{

GridViewRow row = myGridView.Rows[e.RowIndex];

if (row != null)

TextBox t = row.FindControl("TextBox1") as TextBox;

if (t != null)

{
Response.Write("The Text Entered is" + t.Text);

Paging:

Paging can also be easily enabled in the grid view control. Its just like DataGrid from Asp.net 1.1.
First you need to make set the allow paging property to true. And you can also set the page size.
Here is a small code sample that will enable paging.

// Grid View Paging

void myGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)


{

myGridView.PageIndex = e.NewPageIndex;

BindData();

Here is a small image shown below of paging. I have limited the page size to 3 so that the
distribution of page will take place. In the image below we are in the page number 2.

Using SqlDataSource to execute commands:

You can also use the powerful SqlDataSource control to run and make your query. The
SqlDataSource also contains the QUERY builder

interface which can enhance the user experience in making SQL Queries. Apart from the
SELECT query there are also INSERT, DELETE and UPDATE query builders wizards that you
can use in your application.

When you use SqlDataSource you gets the advantage of having the paging, sorting implemented
automatically which is pretty cool in some cases.

In the next article we will see some more features of the Grid View control. I hope you liked the
article

Happy Programming !
The ASP.NET 1.x DataGrid control requires you to write a lot of custom code to handle
common operations such as paging, sorting, editing, and deleting data. For example,
while the DataGrid control can raise events when the user clicks to save or cancel
changes, it doesn't offer much more than that. If you want to store changes to a persistent
medium, such as a database, you have to handle the UpdateCommand event yourself,
retrieve changed values, prepare a SQL command, and then proceed from there to
commit the update.

ASP.NET 2.0 enhances the data-binding architecture, introducing a new family of


components—the data source objects—which act as a bridge between data-bound
controls and ADO.NET objects. These source objects promote a slightly different
programming model and provide for new features and members. For data reporting
purposes, your ASP.NET 2.0 applications should use the newest grid control—the
GridView. The familiar DataGrid control is still supported, but it doesn't take full
advantage of the specific capabilities of data source components.

The GridView control is the successor to the DataGrid and extends it in a number of
ways. First, it fully supports data source components and can automatically handle data
operations, such as paging, sorting, and editing, provided its bound data source object
supports these capabilities. In addition, the GridView control offers some functional
improvements over the DataGrid. In particular, it supports multiple primary key fields
and exposes some user interface enhancements and a new model for handling and
canceling events.

The GridView comes with a pair of complementary view controls: DetailsView and
FormView. By combining these controls, you can easily set up master/detail views using
very little code and sometimes no code at all

More information at

Asp.net 2.0

<connectionStrings>
<add name="ConnString" connectionString="Data Source=ServerName;Initial
Catalog=DBNAME;Integrated Security=True;"
providerName="System.Data.SqlClient"/>
connectionStrings>
Code Behind

Dim con As String =


System.Configuration.ConfigurationManager.ConnectionStrings("ConnString").Connecti
onString

Responses
Author: RamarajSundaram 26 Jul 2006Member Level: DiamondRating:
Points: 2
In .NET 2.0 we are using GridView. More or less Datagrid and GridView both are
same.

Author: vangala shekar reddy 26 Jul 2006Member Level: SilverRating:


Points: 2
refer the following link......

http://msdn2.microsoft.com/en-us/library/05yye6k9.aspx

You have some extra facilities and fetures in grid view than datagrid......

Author: vamshi krishna 26 Jul 2006Member Level: GoldRating: Points: 2


the gridview and the datagrid controls have a different foundation. to enable easy
migration from existing pages, the gridview preserves the datagrid object model
as much as possible. however, you shouldn't expect 100% compatibility between
datagrid-based code and new gridview-based code.

another key difference between the datagrid and gridview controls lies in the
adaptive user interface. unlike the version 1.1 datagrid, the gridview can render
on mobile devices, too. in other words, to build reports on mobile devices, you
can use the same grid control you would use for desktop pages. The datagrid in
version 2.0 can also render adaptively, but its UI capabilities are not quite as rich
as those of the gridview. ASP.NET 2.0, the datagrid control has been enhanced
to support common control features such as themes and personalization.
refer this link http://www.codeproject.com/aspnet/GridViewInsideGridView.asp

Author: Renuka Rajamanickam 26 Jul 2006Member Level: BronzeRating:


Points: 2
GridView is a composite data-bound control and shares a common set of
methods and properties with all other data-bound controls, including
DropDownList, DetailsView, and ListBox.

GridView can render on mobile devices.

Grid view Control take care automatically deletes or updates records from the
datasource.

Author: hakkim sherif 17 May 2007Member Level: BronzeRating: Points: 2


In datagrid you cannot set a permisiion level........

In gridview you can do the access level............

Author: saran 07 Dec 2007Member Level: BronzeRating: Points: 2


In data grid paging, inserting, updating, deleting are implementing by coding. In
data view automatically generates the inserting, updating, deleting without user
writing the code. In data grid no image template column, whereas dataview have
image template column
sorting: In DataGrid code requires handling the SortCommand event and rebind
grid required. In case of GridView no additional code required.
Paging: In DataGrid requires code to handle the PageIndexChanged event and
rebind grid required. In case of GridView no additional code required. It also
supports customized appearance.
Data binding: Like GridView DataGrid cannot bind with new datasource control in
ASP.NET 2.0.
Updating data: DataGrid requires extensive code to update operation on data.
GridView requires little code. Code like exceptions handling for database part.
Events: GridView supports events fired before and after database updates. In
DataGrid less events supported as compared to GridView.
Links - http://msdn.microsoft.com/msdnmag/issues/04/08/GridView/#S1
http://www.wwwcoder.com/main/parentid/459/site/3573/68/default.aspx
http://www.vbdotnetheaven.com/UploadFile/nikhil_be_it/GridViewInsideGridView
05232006004636AM/GridViewInsideGridView.aspx

Author: Kumar Velu 20 Jul 2008Member Level: DiamondRating: Points: 6


The GridView control is the successor to the DataGrid control. Like the DataGrid
control, the GridView control was designed to display data in an HTML table.
When bound to a data source, the DataGrid and GridView controls each display
a row from a DataSource as a row in an output table.

Both the DataGrid and GridView controls are derived from the WebControl class.
Although it has a similar object model to that of the DataGrid control, the
GridView control also has a number of new features and advantages over the
DataGrid control, which include:

Richer design-time capabilities.

Improved data source binding capabilities.

Automatic handling of sorting, paging, updates, and deletes.

Additional column types and design-time column operations.

A Customized pager user interface (UI) with the PagerTemplate property.

Differences between the GridView control and the DataGrid control include:

Different custom-paging support.

Different event models.

Author: UltimateRengan 29 Jul 2008Member Level: DiamondRating: Points:


1
DataGrid:
The DataGrid Web control provides the greatest feature set of the three data
Web controls, with its ability to allow the end-user to sort, page, and edit its data.
The DataGrid is also the simplest data Web control to get started with, as using it
requires nothing more than adding a DataGrid to the Web page and writing a few
lines of code. The ease of use and impressive features comes at a cost, though,
namely that of performance: the DataGrid is the least efficient of the three data
Web controls, especially when placed within a Web form.
DataList:
With its templates, the DataList provides more control over the look and feel of
the displayed data than the DataGrid. Using templates, however, typically
requires more development time than using the DataGrid's column types. The
DataList also supports inline editing of data, but requires a bit more work to
implement than the DataGrid. Unfortunately, providing paging and sorting
support in the DataList is not a trivial exercise. Making up for these lacking built-
in features, the DataList offers better performance over the DataGrid.
Repeater:
Finally, the Repeater control allows for complete and total control of the rendered
HTML markup. With the Repeater, the only HTML emitted are the values of the
databinding statements in the templates along with the HTML markup specified
in the templates—no "extra" HTML is emitted, as with the DataGrid and DataList.
By requiring the developer to specify the complete generated HTML markup, the
Repeater often requires the longest development time. Furthermore, the
Repeater does not offer built-in editing, sorting, or paging support. However, the
Repeater does boast the best performance of the three data Web controls. Its
performance is comparable to the DataList's, but noticeably better than the
DataGrid's

Have a nice day


SAP B1

Author: Sridhar R 23 Aug 2008Member Level: DiamondRating: Points: 5


Datagrid..
1.Code requires to handle the SortCommand event and rebind grid required.
2.Code requires to handle the PageIndexChanged.
3.Need extensive code for update operation on data.
4.When compared to gridview less events supported.

gridView..
1.No code required.
2.No code required for PageIndexChanged.
3.Needs little code for update operation.
4.GridView supports events fired before and after database updates

Regards
Sridhar R
No

Re: What is difference b/w Data Grid in ASP.Net 1.1 and


Gridview in 2.0
Answer Gridview have More properties and 2 Sudhir
events than datagrid.
#3 Kunnure
Auto delete,Edit,auto
column,rowbound,rowdeleteing and many
more.
Grid view is more user friendly than
gridview.
Is This Answer Correct ? 1 Yes 0 No

Re: What is difference b/w Data Grid in ASP.Net 1.1 and


Gridview in 2.0
Answer datagrid is centralized by itemcommand 0 Ishbandhu
property but
#4
gridview is not

Is This Answer Correct ? 1 Yes 0 No

Re: What is difference b/w Data Grid in ASP.Net 1.1 and


Gridview in 2.0
Answer Gridview have auto delete,Edit,auto 0 Mukesh
# 5 column,rowbound,rowdeleteing and many Sharma
more.

Is This Answer Correct ? 3 Yes 0 No

Re: What is difference b/w Data Grid in ASP.Net 1.1 and


Gridview in 2.0
Answer Datagrid is centralized by itemcommand 0 Mukesh
property but
#6 Sharma(mca) ,
gridview is not.
Hapur,gzb
Gridview have auto delete,Edit,auto
column,rowbound,rowdeleteing and many
more.

Is This Answer Correct ? 0 Yes 0 No

Re: What is difference b/w Data Grid in ASP.Net 1.1 and


Gridview in 2.0
Answer Datagrid is centralized by itemcommand 1 A V Suresh
# 7 property but
gridview is not.
Grid view is more user friendly than
gridview.

Is This Answer Correct ? 1 Yes 0 No

Re: What is difference b/w Data Grid in ASP.Net 1.1 and


Gridview in 2.0
Answer In gridview paging is also impletes by 5 Nisha
# 8 user
Is This Answer Correct ? 1 Yes 0 No

Re: What is difference b/w Data Grid in ASP.Net 1.1 and


Gridview in 2.0
Answer using gridview we can transfore the 5 Nisha Patel
control one page to
#9
another page.ex..if i create one master
page, and one detail
(child) . we can provide easily link
from master page to
detail(child) page.and transfer on that
page. its a main
benifit of using gridview , i think
so........

Is This Answer Correct ? 0 Yes 1 No

You might also like