Beruflich Dokumente
Kultur Dokumente
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.
What is a GridView?
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.
GridView Fields
Column Name
Description
BoundColumn
HyperLinkColumn
ButtonColumn
TemplateColumn
CommandField
BoundColumn
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.
HyperLinkColumn
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.
TemplateColumn
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.
By clicking the Edit Templates option, it opens the Template field where we can see
controls that can be added like Label, CheckBox, and even a GridView.
CommandField
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 ofEditItemIndex 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. It's up to
the programmer to handle this event in the code. The typical logic
sets EditItemIndex to the selected row, and then rebinds the data to the grid.
When EditItemIndex is set to a particular row, the EditCommandColumn displays
"update" and "cancel" buttons for that row ("edit" is still displayed for the other rows).
These buttons cause the UpdateCommand andCancelCommand events to be thrown,
respectively.
Description
DataBinding
DataBound
Disposed
Init
Load
PageIndexChanged
PageIndexChanging
Name
Description
operation.
PreRender
RowCancelingEdit
RowCommand
RowCreated
RowDataBound
RowDeleted
RowDeleting
RowEditing
RowUpdated
RowUpdating
SelectedIndexChange
d
Sorting
Unload
These events are all listed in the MSDN, and here I have given a few events which are
frequently used in our day to day projects:
PageIndexChanging
This event occurs when the property of the grid AllowPaging is set to true, and in the
code behind thePageIndexChanging event is fired.
Paging
The DataGrid provides the means to display a group of records from the data source
(for example, the first 10), 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.
Collapse | Copy Code
//AllowPaging="True"
//fires when the property AllowPaging is set to True
GridView2.PageIndex = e.NewPageIndex;
//Datasource method
TempTable();
RowCommand
The DataGrid fires the RowCommand event when any button is pressed. We can given
any name as command name, and based on that, the check will be done and the loop
will be executed.
Collapse | Copy Code
//OnRowCommand="GridView6_RowCommand"
//CommandName="view" CommandArgument='<%# Bind("id") %>'
protected void GridView6_RowCommand(object sender, GridViewCommandEventArgs e)
{
//this will check whether the command name is equal to view. If it is
//equal to view the it will go inside the loop.
if (e.CommandName == "view")
{
//to find which row is clicked
int row = int.Parse(e.CommandArgument.ToString());
StringBuilder sb = new StringBuilder();
sb.Append("<script language="'javascript'">\r\n");
//javascript to navigate to view page.
sb.Append(" window.open('View.aspx?id=" + row + "',
null,'width=350,height=300,scrollbars=yes,left=350,top=200,right=5,bottom=5');");
sb.Append("</script>");
if (!this.IsClientScriptBlockRegistered("BindScript"))
{
RegisterClientScriptBlock("openScript", sb.ToString());
}
}
RowCreated
The DataGrid fires the RowCreate event when a new row is created.
Collapse | Copy Code
//OnRowCreated="GridView3_RowCreated"
protected void GridView3_RowCreated(object sender, GridViewRowEventArgs e)
{
//When a child checkbox is unchecked then the header checkbox will also be unchecked.
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState ==
DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
{
CheckBox chkBxSelect = (CheckBox)e.Row.Cells[1].FindControl("chkselect");
CheckBox chkBxHeader = (CheckBox)this.GridView3.HeaderRow.FindControl("chkHeader");
chkBxSelect.Attributes["onclick"] = string.Format("javascript:ChildClick(
this,'{0}');", chkBxHeader.ClientID);
}
}
RowDeleting
The DataGrid fires the RowDeleting event when the command name is given as Delete.
Collapse | Copy Code
//OnRowDeleting="GridView3_RowDeleting"
//CommandName="delete"
protected void GridView3_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//finding the row index of which row is selected.
int row = e.RowIndex;
//deleteing the temp row(or your delete query that will delete the row from
//the database
Temp.Rows[row].Delete();
//reassigning the datasource
GridView3.DataSource = Temp;
GridView3.DataBind();
}
RowUpdating
The DataGrid fires the RowUpdating event when the command name is given as
Update.
Collapse | Copy Code
//OnRowUpdating="GridView3_RowUpdating"
CommandName="update"
protected void GridView3_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//maintaining the row index to intial position
GridView3.EditIndex = e.RowIndex;
//reassigning the datasource
GridView3.DataSource = Temp;
GridView3.DataBind();
}
RowEditing
The DataGrid fires the RowEditing event when the command name is given as Edit.
Collapse | Copy Code
/OnRowEditing="GridView3_RowEditing"
//CommandName="edit"
protected void GridView3_RowEditing(object sender, GridViewEditEventArgs e)
{
//changing the index of the grid.
GridView3.EditIndex = e.NewEditIndex - 1;
//finding the row of the grid
int row = e.NewEditIndex;
//updating the rows inside the grid
Temp.Rows[row]["name"] = ((TextBox)GridView3.Rows[e.NewEditIndex].FindControl(
"txtname")).Text;
Temp.Rows[row]["gender"] = ((DropDownList)GridView3.Rows[e.NewEditIndex].FindControl(
"ddlgender")).Text;
Temp.Rows[row]["email"] = ((TextBox)GridView3.Rows[e.NewEditIndex].FindControl(
"txtemail")).Text;
Temp.Rows[row]["salary"] = ((TextBox)GridView3.Rows[e.NewEditIndex].FindControl(
"txtsalary")).Text;
Temp.AcceptChanges();
//total of the salary and displaying it in footer.
Total = decimal.Parse(Temp.Compute("sum(Salary)", "Salary>=0").ToString());
//maintaining the total value in the session
Session["Salary"] = Total;
//reassigning the datasource
GridView3.DataSource = Temp;
GridView3.DataBind();
}
RowDatabound
The DataGrid fires the RowDatabound event when a data row is bound to data in
a GridView control.
Collapse | Copy Code
//OnRowDataBound="GridView4_RowDataBound"
Sorting
Data in a grid is commonly sorted by clicking the header of the column to sort. Sorting
in a DataGrid can be enabled by setting AllowSorting to true. When enabled, the grid
renders LinkButton controls in the header for each column. When the button is clicked,
the grid's SortCommand event is thrown. It's up to the programmer to handle this
event in the code. Because DataGrid always displays the data in the same order it
occurs in the data source, the typical logic sorts the data source, and then rebinds the
data to the grid.
Collapse | Copy Code
//AllowSorting="True"
//OnSorting="GridView2_Sorting"
//SortExpression="name"
protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)
{
//to check whether to display in ascending order or descending order
if (e.SortExpression.Trim() == this.SortField)
this.SortDirection = (this.SortDirection == "D" ? "A" : "D");
else
this.SortDirection = "A";
this.SortField = e.SortExpression;
TempTable();
}
<script type="text/javascript">
var TotalChkBx;
var Counter;
window.onload = function()
{
TotalChkBx = parseInt('<%= this.GridView3.Rows.Count %>');
Counter = 0;
}
function SelectAll(CheckBox)
{
var TargetBaseControl = document.getElementById('<%= this.GridView3.ClientID %>');
var TargetChildControl = "chkselect";
var Inputs = TargetBaseControl.getElementsByTagName("input");
for(var n = 0; n < Inputs.length; ++n)
if(Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl,0) >= 0)
Inputs[n].checked = CheckBox.checked;
Counter = CheckBox.checked ? TotalChkBx : 0;
}
function ChildClick(CheckBox, HCheckBox)
{
var HeaderCheckBox = document.getElementById(HCheckBox);
if(CheckBox.checked && Counter < TotalChkBx)
Counter++;
else if(Counter > 0)
Counter--;
if(Counter < TotalChkBx)
HeaderCheckBox.checked = false;
else if(Counter == TotalChkBx)
HeaderCheckBox.checked = true;
}
</script>
onclick="javascript:SelectAll(this);"
To maintain the grid header in a fixed state, a style sheet is used in the source code:
<style type="text/css">.DataGridFixedHeader {
BACKGROUND: url(Images/grid_header.jpg) repeat-x;
POSITION: relative; TOP: expression(this.offsetParent.scrollTop); HEIGHT: 27px }
</style>
<div style="width:80%; height:250px; overflow:auto;" >
<asp:GridView ID="GridView1" runat="server"
Width="100%" AutoGenerateColumns="False"
CellPadding="4" DataKeyNames="id"
ForeColor="#333333" GridLines="None"
OnRowCreated="GridView1_RowCreated"
AllowPaging="True" AllowSorting="True"
OnPageIndexChanging="GridView1_PageIndexChanging" OnSorting="GridView1_Sorting"
PageSize="2" OnRowCommand="GridView1_RowCommand"
OnRowDeleting="GridView1_RowDeleting"
OnRowEditing="GridView1_RowEditing">
....
....
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White"
CssClass="gridHeader DataGridFixedHeader" />
.....
.....
</asp:GridView>
</div>
Excel
Collapse | Copy Code
PDF
Collapse | Copy Code
row, but in a DataList, we can have five or six rows per row. For a Repeater control, the
data records to be displayed depend upon the templates specified, and the only HTML
generated is the due to the templates.
In addition to these, DataGrid has in-built support for sorting, filtering, and paging the
data, which is not possible when using a DataList, and for a Repeater control, we would
require to write explicit code to do paging.