You may
wonder that why I have chosen topic on GridView control, when there are lot of
material available on internet for GridView. But this article focus on closer
look on GridView control, my target audience will be novice to GridView
control.
Also I will
try my best to explain different aspects of GridView.So let's
ready to have closer look at GridView control.
What is GridView control?
GridView is
one of the robust Data Bound control in Visual Studio control gallery to display
data in tabular format. GridView control render as HTML table in browser.
Why we use GridView control?
Following
are some applications of GridView control.
- Show data in tabular format for
reporting purpose.
- Provide mechanism to display
report for application.
- We can use some inbuilt
features of GridView such as paging, sorting, editing, and deleting to
enhance user experience.
How to use GridView control?
It's really
easy; you need to drag GridView control on web form. Default markup for GridView
design is as follows
Also
Default GridView markup source is as follows
<asp:GridView ID="GridView1"
runat="server">
</asp:GridView>
ID
indicates unique identifier for GridView control.
How to Bind Data to GridView control
?
As I said
above GridView is Data Bound control, the term Data Bound means we are presenting
data in GridView from data source such as Data from DataBase,In memory data etc.
For simplicity we will use In Memory DataTable for understanding.
In Closer
look at GridView control (Part 1) we will concentrate on
AutoGeneratedColumns of GridView.
I will use
simple StudentName,StudentMarks In memory DataTable to demonstrate binding in
GridView. In memory DataTable will be as follows

We will
store above DataTable in session variable property, so that it will be
accessible across postback. Following is code to generate InMemory DataTable
/// <summary>
/// This property is used as container for in memory data
/// </summary>
private DataTable InMemoryDataTable
{
get { return (DataTable)Session["InMemoryDataTable"]; }
set {
Session["InMemoryDataTable"] = value; }
}
This
property is required to store InMemory DataTable across postbacks.
/// <summary>
/// In this method we are generating default in memory data
/// This data will be stored in InMemoryDataTable session
/// </summary>
private void GenerateDefaultInMemoryData()
{
try
{
DataTable
dtInMemory = new DataTable();
DataRow
dr;
dtInMemory.Columns.Add("StudentId", typeof(int));
dtInMemory.Columns.Add("StudentName", typeof(string));
dtInMemory.Columns.Add("StudentMarks", typeof(int));
//contruct in
memory data
dr = dtInMemory.NewRow();
dr["StudentId"]
= 1;
dr["StudentName"]
= "abc";
dr["StudentMarks"]
= 50;
dtInMemory.Rows.Add(dr);
dr = dtInMemory.NewRow();
dr["StudentId"]
= 2;
dr["StudentName"]
= "xyz";
dr["StudentMarks"]
= 40;
dtInMemory.Rows.Add(dr);
dr = dtInMemory.NewRow();
dr["StudentId"]
= 3;
dr["StudentName"]
= "qwe";
dr["StudentMarks"]
= 80;
dtInMemory.Rows.Add(dr);
dr = dtInMemory.NewRow();
dr["StudentId"]
= 4;
dr["StudentName"]
= "pqr";
dr["StudentMarks"]
= 90;
dtInMemory.Rows.Add(dr);
//store it in
InMemoryDataTable session
InMemoryDataTable = dtInMemory;
}
catch
{
throw;
}
}
Above
function GenerateDefaultInMemoryData is used to generate default data, this
function will be consumed in Page_Load and whenever we need to reset InMemory
Data.
/// <summary>
/// In this method we are binding data to GridView from in memory
/// DataTable
/// </summary>
private void BindGridView()
{
try
{
//check if
InMemoryDataTable contains data
if
(InMemoryDataTable != null &&
InMemoryDataTable.Rows.Count > 0)
{
//bind
gridview
GridView1.DataSource =
InMemoryDataTable;
GridView1.DataBind();
}
else
{
//clear
datasource
GridView1.DataSource = null;
GridView1.DataBind();
}
}
catch
{
throw;
}
}
Above function will bind data to
GridView, it will simply assign DataSource as InMemoryDataTable session. After
calling GridVIew1.DataBind () method GridView is completes its DataBinding.
BindGridView() function is called in Page_Load to initailly load GridView.
/// <summary>
/// Page Load
/// </summary>
/// <param
name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object
sender, EventArgs e)
{
if
(!IsPostBack)
{
GenerateDefaultInMemoryData();
BindGridView();
}
}
Above id Page_Load event, we have
called our both methods to Bind GridView. This completes GridView binding.
Important points in GridView binding
- Make sure AutoGeneratedColumns property is set
to true.
- Make sure to call DataBind() method of GridView.
When
you run above code it brings following output in browser
Uptil now GridView control only
served purpose to display data in read only format means we can not manipulate
data inside GridView. What if you want
to Update or Delete record inside GridView. Now will see in detail how to
accomplish Update or Delete inside GridView.
How to Update or Delete row inside GridView ?
Following are simple steps
- Set AutoGenerateDeleteButton
property of GridView to True.
- Set AutoGenerateEditButton
property of GridView to True.
When
you set above two properties, then automatically Edit, Delete link buttons are
embedded in GridViews first column as follows
Now, we need to handle Edit, Delete
link button click event handlers. Following is detailed description
When we click on Edit link button
GridView raises GridView1_RowEditing
event handler, this event gives us opportunity to open selected GridView row in
edit mode, set some client side validations. Following is implementation of GridView1_RowEditing event handler.
/// <summary>
/// Open selected grid view in edit mode
/// </summary>
/// <param
name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowEditing(object
sender, GridViewEditEventArgs e)
{
try
{
GridView1.EditIndex = e.NewEditIndex;
BindGridView();
GridViewRow
row = GridView1.Rows[e.NewEditIndex];
//set default
focus in student name
row.Cells[2].Focus();
//disable
student id updation since it is primary field
row.Cells[1].Enabled = false;
//add client
side validation for student name and student marks
//validation
are as follows
//student
name should not blank
//student
marks should be numeric field
//if
validation fails client side alert will be generated
//this validations will be called when we click on update
link button
LinkButton
lnkUpdate = (LinkButton)row.Cells[0].Controls[0];
if
(lnkUpdate != null && lnkUpdate.Text ==
"Update")
{
string
Name = row.Cells[2].Controls[0].ClientID;
string
Marks = row.Cells[3].Controls[0].ClientID;
lnkUpdate.OnClientClick = "return ValidateStudent('" + Name + "','" + Marks + "');";
}
}
catch
{
throw;
}
}
In above event handler we opened
selected GridView row in edit mode, also set default focus, added clientside
function ValidateStudent() for validation. Following is implementation of
ValidateStudent() function in javascript.
<script type ="text/javascript">
//following javascript validates student name and student marks
//this function is called when we click on update link button
function
ValidateStudent(StudentName,StudentMarks)
{
var Name =
document.getElementById(StudentName).value;
var Marks =
document.getElementById(StudentMarks).value;
var numbers =
"0123456789";
var message =
"";
var isNumeric
= true;
for (i=0;
i<Marks.length; i++)
{
if (numbers.indexOf(Marks.charAt(i),0)
== -1)
{
isNumeric = false;
break;
}
}
if(Name == "")
{
message = "Please
enter student name.";
}
if(Marks == "" || isNumeric == false)
{
if(message
!= "")
{
message
= message + "\n\rPlease enter valid
student marks.";
}
else
{
message
= "Please enter valid student
marks";
}
}
if(message !=
undefined && message != null &&
message != "")
{
alert(message);
return false;
}
return true;
}
</script>
Implementation of ValidateStudent
function is simple to understand its typical function for validation.
Up till now we opened selected GridView
row in edit mode as follows.
You can see for selected GridView
row Update and Cancel LinkButton AutoGenerated.
When we click on Update link button
GridView raises GridView1_RowUpdating
event handler, this event gives us opportunity to update selected GridView row.
Following is implementation GridView1_RowUpdating
event handler.
/// <summary>
/// Update selected gridview row
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowUpdating(object
sender, GridViewUpdateEventArgs e)
{
try
{
//select
gridview row
GridViewRow
row = GridView1.Rows[e.RowIndex];
//find
following details to update in InMemoryDataTable session
int
StudentId = Convert.ToInt16(((TextBox)row.Cells[1].Controls[0]).Text);
string
StudentName = ((TextBox)row.Cells[2].Controls[0]).Text;
int
StudentMarks = Convert.ToInt16(((TextBox)row.Cells[3].Controls[0]).Text);
//update
details in InMemoryDataTable session
if(InMemoryDataTable
!= null && InMemoryDataTable.Rows.Count
> 0)
{
DataRow[]
drToUpdate = InMemoryDataTable.Select("
StudentId = " + StudentId);
//check
if drToUpdate contains data
if
(drToUpdate != null &&
drToUpdate.Length > 0)
{
//update
student name
drToUpdate[0]["StudentName"] = StudentName;
//update
student marks
drToUpdate[0]["StudentMarks"] = StudentMarks;
//reset
gridview in edit mode
GridView1.EditIndex = -1;
//bind
gridview
BindGridView();
}
}
}
catch
{
throw;
}
}
In above event handler we referenced
values inside GridView cells and updated in InMemory session DataTable. Please
give careful attention to GridView control hierarchy, means auto generated link
buttons not directly accessible in code behind we need to find them inside
parent GridView container.
If you want to cancel row update
process, then you can click on cancel linkbutton. When you click in Cancel
linkbutton GridView will raise GridView1_RowCancelingEdit event handler as
follows
/// <summary>
/// Cancel edit of selected gridview row
/// </summary>
/// <param
name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs
e)
{
try
{
GridView1.EditIndex = -1;
BindGridView();
}
catch
{
throw;
}
}
When you set GridView1.EditIndex to
-1 then selected row shown in read only format as follows
This completes GridView selected row
updating.
Important points in GridView row Editing
- Make sure GridView1_RowEditing,
GridView1_RowUpdating event handlers are attached to GridVIew control,
otherwise error is generated.
- To reset GridView row in its original state use GridView1.EditIndex
= -1
When we click on Delete link button GridView
raises GridView1_RowDeleting event
handler, this event gives us opportunity to delete selected GridView row.
Following is implementation of GridView1_RowDeleting
event handler
/// <summary>
/// Delete selected gridview row
/// </summary>
/// <param
name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowDeleting(object
sender, GridViewDeleteEventArgs e)
{
//find
student id to delete
int
StudentId = Convert.ToInt16(GridView1.Rows[e.RowIndex].Cells[1].Text);
//delete it
from data source
if
(InMemoryDataTable != null &&
InMemoryDataTable.Rows.Count > 0)
{
DataRow[]
drDelete = InMemoryDataTable.Select(" StudentId
= " + StudentId);
if
(drDelete != null && drDelete.Length
> 0)
{
//remove
row from data source
InMemoryDataTable.Rows.Remove(drDelete[0]);
//bind
grid view
BindGridView();
}
}
}
In above event handler we have
deleted selected StudentId record from InMemoryDataTable.
When you delete record from GridView
its common practice that we need to show confirm prompt before deleting row as
follows

We need to use special and important
event handler of GridView termed as GridView1_RowDataBound
to show confirm prompt when we click on Delete linkbutton. GridView1_RowDataBound is raised for individual row bind. Following
is implementation of GridView1_RowDataBound
event handler.
/// <summary>
/// Row data bound
/// </summary>
/// <param
name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowDataBound(object
sender, GridViewRowEventArgs e)
{
try
{
if
(e.Row.RowType == DataControlRowType.DataRow)
{
//find
delete link button
LinkButton
lnkDelete = (LinkButton)e.Row.Cells[0].Controls[2];
//add
confirm prompt attributes to lnkDelete
if
(lnkDelete != null && lnkDelete.Text == "Delete")
{
lnkDelete.OnClientClick = "return confirm('Are you sure ?');";
}
}
}
catch
{
throw;
}
}
Above event handler is simple to
understand, in this handler onclientclick attributes are added for confirm
prompt, these attributes are only added for DataRow inside GridView.
Important points in GridView row Deleting
- Make sure GridView1_RowDeleting event handler is attached to
GridVIew control, otherwise error is generated.
So, this completes Closer look at GridView control Part – 1.
Reference : http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.aspx
In next subsequent parts I will try
to explore GridView events, BoundFields,TemplateFields,Custom Paging,Sorting.
I hope this article gives basic
understanding of GridView control.