SlideShare a Scribd company logo
GRID VIEW PPT
 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.
GRID VIEW PPT
<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.
GRID VIEW PPT
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.
GRID VIEW PPT
 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.
GRID VIEW PPT
GRID VIEW PPT
 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.
GRID VIEW PPT
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.
GRID VIEW PPT
 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

More Related Content

What's hot (20)

PPT
RichControl in Asp.net
Bhumivaghasiya
 
PPTX
Ado.Net Tutorial
prabhu rajendran
 
PPT
ADO .Net
DrSonali Vyas
 
PPTX
PHP FUNCTIONS
Zeeshan Ahmed
 
PDF
Applets
Prabhakaran V M
 
PPS
Procedures functions structures in VB.Net
tjunicornfx
 
PPT
Textbox n label
chauhankapil
 
PPTX
Nested queries in database
Satya P. Joshi
 
PDF
Asp .net web form fundamentals
Gopal Ji Singh
 
PPTX
Java swing
Apurbo Datta
 
PPT
Servlet life cycle
Venkateswara Rao N
 
PPT
Web controls
Sarthak Varshney
 
PPTX
Notification android
ksheerod shri toshniwal
 
PPT
Threads And Synchronization in C#
Rizwan Ali
 
PPT
vb.net Constructor and destructor
suraj pandey
 
PPTX
JAVA AWT
shanmuga rajan
 
PPTX
VB.NET:An introduction to Namespaces in .NET framework
Richa Handa
 
PPTX
Exception Handling in VB.Net
rishisingh190
 
PPT
Asp.net control
Paneliya Prince
 
RichControl in Asp.net
Bhumivaghasiya
 
Ado.Net Tutorial
prabhu rajendran
 
ADO .Net
DrSonali Vyas
 
PHP FUNCTIONS
Zeeshan Ahmed
 
Procedures functions structures in VB.Net
tjunicornfx
 
Textbox n label
chauhankapil
 
Nested queries in database
Satya P. Joshi
 
Asp .net web form fundamentals
Gopal Ji Singh
 
Java swing
Apurbo Datta
 
Servlet life cycle
Venkateswara Rao N
 
Web controls
Sarthak Varshney
 
Notification android
ksheerod shri toshniwal
 
Threads And Synchronization in C#
Rizwan Ali
 
vb.net Constructor and destructor
suraj pandey
 
JAVA AWT
shanmuga rajan
 
VB.NET:An introduction to Namespaces in .NET framework
Richa Handa
 
Exception Handling in VB.Net
rishisingh190
 
Asp.net control
Paneliya Prince
 

Similar to GRID VIEW PPT (20)

PDF
Step by Step Asp.Net GridView Tutorials
Nilesh kumar Jadav
 
DOCX
Grid view control
Paneliya Prince
 
PPT
ASP.NET Session 13 14
Sisir Ghosh
 
PPTX
Grid View Control CS
sunmitraeducation
 
PPTX
Grid Vew Control VB
sunmitraeducation
 
PPT
Chapter12 (1)
Rajalaxmi Pattanaik
 
PPTX
Chapter 16
application developer
 
DOCX
Add row in asp.net Gridview on button click using C# and vb.net
Vijay Saklani
 
DOCX
Add row in asp.net Gridview on button click using C# and vb.net
Vijay Saklani
 
DOC
The most basic inline tag
April Anne Emmanuel
 
PPTX
Detail view in distributed technologies
jamessakila
 
PPTX
Work with data in ASP.NET
Peter Gfader
 
PPTX
Application of Insert and select notes.ppt x
doxafo4842
 
PDF
Custom Paging with GridView
TO THE NEW Pvt. Ltd.
 
PPT
Data controls ppt
Iblesoft
 
PDF
Ch7.2-Controls for Programm 001-193819qk
romoeogonzales
 
PPT
Fixing an annoying GridView problem
Roger Pence
 
PDF
Aspnet.grid view
ibrahimkhan
 
DOCX
Framework 4
Rajesh Kumar Ranjan
 
PPTX
Yogesh kumar kushwah represent’s
Yogesh Kushwah
 
Step by Step Asp.Net GridView Tutorials
Nilesh kumar Jadav
 
Grid view control
Paneliya Prince
 
ASP.NET Session 13 14
Sisir Ghosh
 
Grid View Control CS
sunmitraeducation
 
Grid Vew Control VB
sunmitraeducation
 
Chapter12 (1)
Rajalaxmi Pattanaik
 
Add row in asp.net Gridview on button click using C# and vb.net
Vijay Saklani
 
Add row in asp.net Gridview on button click using C# and vb.net
Vijay Saklani
 
The most basic inline tag
April Anne Emmanuel
 
Detail view in distributed technologies
jamessakila
 
Work with data in ASP.NET
Peter Gfader
 
Application of Insert and select notes.ppt x
doxafo4842
 
Custom Paging with GridView
TO THE NEW Pvt. Ltd.
 
Data controls ppt
Iblesoft
 
Ch7.2-Controls for Programm 001-193819qk
romoeogonzales
 
Fixing an annoying GridView problem
Roger Pence
 
Aspnet.grid view
ibrahimkhan
 
Framework 4
Rajesh Kumar Ranjan
 
Yogesh kumar kushwah represent’s
Yogesh Kushwah
 
Ad

Recently uploaded (20)

PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPTX
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PPTX
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
Horarios de distribución de agua en julio
pegazohn1978
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
Ad

GRID VIEW PPT

  • 2.  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.
  • 3.  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.
  • 4.  The GridView control displays the values of a data source in a table.  Each column represents a field, while each row represents a record.
  • 5.  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.
  • 7. <asp:GridView ID="gridService" runat="server”> </asp:GridView>  This article shows how to use a GridView control in ASP.Net using C# code behind.
  • 8. 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.
  • 9.  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.
  • 10.  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.
  • 11.  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.
  • 12.  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) { } 
  • 13.  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.
  • 15. 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); } }
  • 16. 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; }
  • 17. 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
  • 18.  Therefore you will see the four records in GridView, at each page.
  • 19.  When you click on the next link, you will get the next records.
  • 20.  If you click on any column, record will be sort accordingly.
  • 21.  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
  • 22. 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.
  • 23.  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.
  • 24.  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.
  • 25.  You can use BoundField by using the smart tag of GridView control as follows.
  • 26.  Click on Edit column link and provide text on HeaderText and DataField. Uncheck the Auto-generate fields’ checkbox.
  • 27.  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.
  • 29.  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.
  • 30.  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.
  • 33.  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.
  • 35. 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.
  • 36. 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.
  • 37. 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.)
  • 38.  This event occurs when the property of the grid AllowPaging is set to true, and in the code behind the PageIndexChanging event is fired.
  • 39.  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.
  • 40.  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();
  • 41.  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;
  • 42. 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();}
  • 43. 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();
  • 44. 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();}
  • 45. 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();}
  • 46. 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();}
  • 47.  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.
  • 49.  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.