Skip to main content
 I have seen lot of beginners struggle with GridView
and it is not working.
 To solve this to some extent, I have created an
application with most of the events and properties of
GridView.
 This may be helpful for getting a clear idea about
working with GridView.
 This application also has a few JavaScript code
snippets and stylesheets which may be useful to add
some values to the GridView.
 Hope this article will be simple and sufficient.
 The DataGrid or GridView control displays data in
tabular form, and it also supports selecting, sorting,
paging, and editing the data inside the grid itself.
 The DataGrid or GridView generates a BoundColumn
for each field in the data source
(AutoGenerateColumns=true).
 By directly assigning the data source to the GridView,
the data can be rendered in separate columns, in the
order it occurs in the data source.
 By default, the field names appear in the grid's
column headers, and values are rendered in text
labels.
 A default format is applied to non-string values and
it can be changed.
 The GridView control displays the values of a data
source in a table.
 Each column represents a field, while each row
represents a record.
 Binding to data source controls, such as SqlDataSource.
 Built-in sort capabilities.
 Built-in update and delete capabilities.
 Built-in paging capabilities.
 Built-in row selection capabilities.
 Programmatic access to the GridView object model to
dynamically set properties, handle events, and so on.
 Multiple key fields.
 Multiple data fields for the hyperlink columns.
 Customizable appearance through themes and styles.
<asp:GridView ID="gridService"
runat="server”>
</asp:GridView>
 This article shows how to use a GridView
control in ASP.Net using C# code behind.
In this we perform the following operations on
GridView.
 Bind data to GridView column
 Edit data in GridView
 Delete rows from GridView
 Update row from database
I have a sample example that explains all the
preceding operations.
 GridView is most feature-rich control in ASP.NET.
 Apart from displaying the data, you can perform
select, sort, page, and edit operations with GridView
control.
 If your application is working with huge amount of data, then
it is not good and efficient to display all records at a time.
 Paging is a technique, which divides the records into pages.
 In DataGrid, the default page size is ten.
 The DataGrid supports two kinds of paging:
1. Default paging, and
2. Custom paging
 In default paging, the entire records are fetched from the
database, then the DataGrid selects records from entire set of
data, according to page size, to display it in DataGrid.
 In custom paging, developers have to write code for selective
retrieve of the records from entire records to display in each
page.
 Custom paging provides better performance than default
paging.
 To enable default paging, set the AllowPaging property of the
GridView to true.
 Default value of PageSize property is 10.
 Set PageSize property to display the number of records per
page according to need of your application.
 The default event of DataGrid control is
SelectedIndexChanged.
 The main event that is responsible for paging is
PageIndexChanged event.
 When the user clicks on paging link on the GridView, page is
postback to the server. On postback, PageIndexChanged event
of DataGrid is called. Set the PageIndex property of
DataGrid is as follows.
GridView1.PageIndex= e.NewPageIndex;
 When user clicks on the paging link, new page index is set.
GridView supports bidirectional paging.
 To enable sorting, set the AllowSorting property of the
GridView as true.
 The main event behind sorting in GridView is Sorting event.
protected void GridView1_Sorting(object sender,
GridViewSortEventArgs e)
{
}

 GridViewSortEventArgs parameter supports
SortDirection and SortExpression property.
 SortDirection property is used to sort the grid column
using ascending and descending order.
 SortExpression property is the column name that you
need to sort.
Example
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.WebControls;
public partial class GridViewDemo : System.Web.UI.Page
{
SqlConnection conn;
SqlDataAdapter adapter;
DataSet ds;
string str="EmpID";
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
FillGridView(str);
}
}
protected void FillGridView(string str)
{
string cs =
ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
try
{
conn = new SqlConnection(cs);
adapter = new SqlDataAdapter("select * from tblEmps order
by "+str, conn);
ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (Exception ex)
{
Label1.Text = "ERROR :: " + ex.Message;
}
finally
{
ds.Dispose();
conn.Dispose();
}}
protected void GridView1_Sorting(object sender,
GridViewSortEventArgs e)
{
str = e.SortExpression;
FillGridView(str);
}
protected void GridView1_PageIndexChanging(object sender,
GridViewPageEventArgs e)
{
GridView1.PageIndex= e.NewPageIndex;
FillGridView(str);
}
}
Execute the above code, you will get the output according to data in the
database table. Default value of PageSize property is 10. We have set this value
as 4
 Therefore you will see the four records in GridView, at
each page.
 When you click on the next link, you will get the next
records.
 If you click on any column, record will be sort
accordingly.
 Suppose that there is no data in database table or no
results are returned from the data source then you can
display user friendly message in GridView that there is
no record available.
 The GridView supports two properties that are used to
display message when no results are returned.
The two properties are:
 EmptyDataText
 EmptyDataTemplate
Column Name Description
BoundColumn To control the order and rendering of columns.
HyperLinkColumn Presents the bound data in HyperLink controls
ButtonColumn
Bubbles a user command from within a row to
the grid event handler
TemplateColumn
Controls which controls are rendered in the
column
CommandField
Displays Edit, Update, and Cancel links in
response to changes in the DataGrid control's
EditItemIndex property.
 By explicitly creating a BoundColumn in the grid's
Columns collection, the order and rendering of each
column can be controlled.
 In the BoundField properties, when the DataField and
the SortExpressions are given, sorting and rendering
the data can be easily done.
 DataField: It bounds the column data of database table.
 DataFormatString: This property is used for string
formats.
 HeaderText: It displays the custom header text on
GridView.
 ReadOnly: It makes the field as non-editable.
 Visible: It is a Boolean property that enables you to
make the column visible or hide according to value true
or false.
 NullDisplayText: If there is no data in table, then you
can use this property to display NULL message.
 You can use BoundField by using the smart tag of
GridView control as follows.
 Click on Edit column link and provide text on HeaderText and
DataField. Uncheck the Auto-generate fields’ checkbox.
 A HyperLinkColumn presents the bound data in
HyperLink controls.
 This is typically used to navigate from an item in the
grid to a Details view on another page by directly
assigning the page URL in NavigationUrl or by
rendering it from the database.
 With a TemplateColumn, the controls which are
rendered in the column and the data fields bound to
the controls can be controlled.
 By using the TemplateColumn, any type of data
control can be inserted.
 AlternatingItemTemplate: This template is used to display
the content at every alternate row.
 EditItemTemplate: It is used when the user edit the records.
 FooterTemplate: As it name suggests that the contents of
this template are displayed at the column footer.
 HeaderTemplate: It displayed the contents at the column
header.
 InsertItemTemplate: When user inserted a new data item,
then the contents of this template are displayed
 ItemTemplate: This template is used for every when
rendered by the GridView.
 The EditCommandColumn is a special column type that
supports in-place editing of the data in one row in the grid.
 EditCommandColumn interacts with another property of the
grid: EditItemIndex.
 By default, the value of EditItemIndex is -1, meaning none of
the rows (items) in the grid are being edited.
 If EditItemIndex is -1, an "edit" button is displayed in the
EditCommandColumn for each of the rows in the grid.
 When the "edit" button is clicked, the grid's EditCommand
event is thrown.
 When EditItemIndex is set to a particular row, the
EditCommandColumn displays "update" and "cancel" buttons
for that row .
 These buttons cause the UpdateCommand and
CancelCommand events to be thrown, respectively.
Name Description
DataBinding Occurs when the server control binds to a data source.
(Inherited from Control.)
DataBound Occurs after the server control binds to a data source.
(Inherited from BaseDataBoundControl.)
Disposed Occurs when a server control is released from memory,
which is the last stage of the server control lifecycle
when an ASP.NET page is requested. (Inherited from
Control.)
Init Occurs when the server control is initialized, which is
the first step in its lifecycle. (Inherited from Control.)
Load Occurs when the server control is loaded into the Page
object. (Inherited from Control.)
PageIndexChanged Occurs when one of the pager buttons is clicked, but
after the GridView control handles the paging
operation.
PageIndexChanging Occurs when one of the pager buttons is clicked, but
before the GridView control handles the paging
operation.
PreRender Occurs after the Control object is loaded but
prior to rendering. (Inherited from Control.)
RowCancelingEdit Occurs when the Cancel button of a row in edit
mode is clicked, but before the row exits edit
mode.
RowCommand Occurs when a button is clicked in a GridView
control.
RowCreated Occurs when a row is created in a GridView
control.
RowDataBound Occurs when a data row is bound to data in a
GridView control.
RowDeleted Occurs when a row's Delete button is clicked,
but after the GridView control deletes the row.
RowDeleting Occurs when a row's Delete button is clicked,
but before the GridView control deletes the row.
RowEditing Occurs when a row's Edit button is
clicked, but before the GridView control
enters edit mode.
RowUpdated Occurs when a row's Update button is
clicked, but after the GridView control
updates the row.
RowUpdating Occurs when a row's Update button is
clicked, but before the GridView control
updates the row.
SelectedIndexChanged Occurs when a row's Select button is
clicked, but after the GridView control
handles the select operation.
SelectedIndexChanging Occurs when a row's Select button is
clicked, but before the GridView control
handles the select operation.
Sorted Occurs when the hyperlink to sort a
column is clicked, but after the GridView
control handles the sort operation.
Sorting Occurs when the hyperlink to sort a
column is clicked, but before the GridView
control handles the sort operation.
Unload Occurs when the server control is
unloaded from memory. (Inherited from
Control.)
 This event occurs when the property of the grid
AllowPaging is set to true, and in the code behind the
PageIndexChanging event is fired.
 The DataGrid provides the means to display a group of
records from the data source and then navigates to the
"page" containing the next 10 records, and so on through
the data.
 Paging in DataGrid is enabled by setting AllowPaging to
true.
 When enabled, the grid will display page navigation buttons
either as "next/previous" buttons or as numeric buttons.
 When a page navigation button is clicked, the
PageIndexChanged event is thrown.
 It's up to the programmer to handle this event in the code.
 The DataGrid fires the RowUpdating event when the
command name is given as Update.
OnRowUpdating="GridView3_RowUpdating"
CommandName="update"protected void
GridView3_RowUpdating(object sender,
GridViewUpdateEventArgs e){
GridView3.EditIndex = e.RowIndex;
GridView3.DataSource = Temp;
GridView3.DataBind();}
AllowPaging="True"
AllowPaging is set to TrueGridView2.PageIndex =
e.NewPageIndex;//Datasource methodTempTable();
 The DataGrid fires the RowEditing event when the
command name is given as Edit.
OnRowEditing="GridView3_RowEditing“
protected void GridView3_RowEditing(object sender,
GridViewEditEventArgs e){
GridView3.EditIndex = e.NewEditIndex - 1;
int row = e.NewEditIndex;
Temp.Rows[row]["name"]
((TextBox)GridView3.Rows[e.NewEditIndex].FindControl(
"txtname")).Text; Temp.Rows[row]["gender"] =
((DropDownList)GridView3.Rows[e.NewEditIndex].FindContro
l( "ddlgender")).Text;
Temp.Rows[row]["email"] =
((TextBox)GridView3.Rows[e.NewEditIndex].FindCon
trol( "txtemail")).Text; Temp.Rows[row]["salary"]
=((TextBox)GridView3.Rows[e.NewEditIndex].FindC
ontrol( "txtsalary")).Text; Temp.AcceptChanges();
Total = decimal.Parse(Temp.Compute("sum(Salary)",
"Salary>=0").ToString());
Session["Salary"] = Total;
GridView3.DataSource = Temp;
GridView3.DataBind();}
Word
protected void btnword_Click(object sender,
EventArgs e){ Response.AddHeader("content-
disposition",
"attachment;filename=Information.doc");
Response.Cache.SetCacheability(HttpCacheability.No
Cache); Response.ContentType =
"application/vnd.word"; System.IO.StringWriter
stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new
HtmlTextWriter(stringWrite); // Create a form to
contain the grid HtmlForm frm = new HtmlForm();
GridView1.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(GridView1);
frm.RenderControl(htmlWrite);
//GridView1.RenderControl(htw);
Response.Write(stringWrite.ToString());
Response.End();}
protected void btnexcel_Click(object sender, EventArgs e){
string attachment = "attachment; filename=Information.xls";
Response.ClearContent(); Response.AddHeader("content-
disposition", attachment); Response.ContentType =
"application/ms-excel"; StringWriter sw = new
StringWriter(); HtmlTextWriter htw = new
HtmlTextWriter(sw);
HtmlForm frm = new HtmlForm();
GridView1.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(GridView1); frm.RenderControl(htw); /
Response.Write(sw.ToString());
Response.End();}
protected void btnpdf_Click(object sender, EventArgs
e){ Response.Clear(); StringWriter sw = new
StringWriter(); HtmlTextWriter htw = new
HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition",
"attachment; filename=Information.pdf");
Response.Write(sw.ToString()); Response.End();}
 Cells: It provides the cell collection of table row which
is being bound.
 DataItem: It represents the data item which is going to
bind with row.
 RowIndex: It provides the index of the bound row.
 RowState: It supports the following values. Alternate,
Normal, Selected, and Edit.
 RowType: It provides the information about the type of
row that is going to bound. It supports the following
values.
DataRow, Footer, Header, NullRow, Pager, and
Separator.
 This is my second article, and if you have any
questions, you can refer to the project attached
because all the code in the article is from the project.
 Further questions or clarifications or mistakes are
welcome.
GRID VIEW PPT