Gridview in ASP.NET 2.0






2.33/5 (8 votes)
Aug 30, 2007
1 min read

56258
It explains about gridview paging and sorting
Introduction
In ASP.NET 2.0 datagrid control is transformed to Gridview with added features.
This article explains about the sorting along paging and adding button control inside the gridview.
Paging and Sorting functions:
In gridview, paging and sorting can be achieved together.
Using the code
The HTML page looks this.
<asp:GridView ID="gvView" runat="server"
PagerSettings-Position="TopAndBottom" AutoGenerateColumns="False"
AllowPaging="True" AllowSorting="True"
OnPageIndexChanging="gvView_PageIndexChanging"
OnSorting="gvView_Sorting" OnRowDataBound="gvView_RowDataBound"
HeaderStyle-CssClass="GridTableHeader"
AlternatingRowStyle-CssClass="GridTableCellsAlt"
RowStyle-CssClass="GridTableCells" >
<PagerStyle HorizontalAlign="left" />
<Columns>
<asp:TemplateField HeaderStyle-CssClass="GridTableHeader" >
<ItemTemplate >
<asp:Button ID="btnViewDetails" Text="ViewDetails" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<HeaderStyle Font-Size="Small" />
</asp:TemplateField>
<asp:BoundField DataField="EmpId" HeaderText="EmpID" SortExpression="EmpId" />
<asp:BoundField DataField="EmpName" HeaderText="EmpName"
SortExpression="EmpName" />
</Columns>
</asp:GridView>
/// Binds the resultset to the datagrid
private void BindDatagrid()
{
DataSet dsData;
try
{
// Populate dataset dsData from the source.
// It may be from database or from the session.
if (dsData!= null)
{
if (dsData.Tables[0].Rows.Count >
PageIndexChanging event will be called whenever the paging button is clicked.
/// Called when the page index is changed
protected void gvView_PageIndexChanging(object sender,
GridViewPageEventArgs e)
{
DataSet dsData = (DataSet)Session["dsData"];
DataTable dtData = dsData.Tables[0];
gvView.DataSource = SortDataTable(dtData, true);
gvView.PageIndex = e.NewPageIndex;
gvView.DataBind();
}
/// Called when the grid coloumn is clicked for sorting
protected void gvView_Sorting(object sender, GridViewSortEventArgs e)
{
DataSet dsData = (DataSet)Session["dsData"];
DataTable dtData = dsData.Tables[0];
GridViewSortExpression = e.SortExpression;
//get the pageindex of the grid.
int pageIndex = gvView.PageIndex;
gvView.DataSource = SortDataTable(dtData, false);
gvView.DataBind();
gvView.PageIndex = pageIndex;
}
The functions GridViewSortDirection and GridViewSortExpression initializes
the default sort direction to ascending and expression to empty string.
The sebsequent sort direction will be decided from the function GetSortDirection.
/// Gets or Sets the gridview sortdirection property
private string GridViewSortDirection
{
get
{
return ViewState["SortDirection"] as string ?? "ASC";
}
set
{
ViewState["SortDirection"] = value;
}
}
/// Gets or Sets the gridview sortexpression property
private string GridViewSortExpression
{
get
{
return ViewState["SortExpression"] as string ?? string.Empty;
}
set
{
ViewState["SortExpression"] = value;
}
}
/// Returns the direction of the sorting
private string GetSortDirection()
{
switch (GridViewSortDirection)
{
case "ASC":
GridViewSortDirection = "DESC";
break;
case "DESC":
GridViewSortDirection = "ASC";
break;
}
return GridViewSortDirection;
}
SortDataTable will sort the datatable based on the page selected
and the sort direction selected.
/// Sorts the resultset based on the sortexpression and the selected column. protected DataView SortDataTable(DataTable dataTable, bool isPageIndexChanging) { if (dataTable != null) { DataView dataView = new DataView(dataTable); if (GridViewSortExpression != string.Empty) { if (isPageIndexChanging) { dataView.Sort = string.Format("{0} {1}", GridViewSortExpression, GridViewSortDirection); } else { dataView.Sort = string.Format("{0} {1}", GridViewSortExpression, GetSortDirection()); } } return dataView; } else { return new DataView(); } }
Button control inside Gridview:
Button control can be added inside the gridview. Button control
can be made visible/invisible dynamically based on the requirement.
e.g.
Drag and drop a gridview from the toolbar into your HTML page.
Add a button into the gridview control. Refer the code snippet below.
<script language ="javascript" type="text/javascript"> //This function is executed when the VIEWDETAILS button in a particular row is clicked, which takes the row's details as parameters and opens the DetailData.aspx with parameters passed in querystring function OpenDetailsPage (EmpId) { var WinSettings = "center:yes;resizable:no;dialogHeight:600px; scroll:no;status:no" window.showModalDialog("DetailData.aspx?ApplicationID="+EmpId, null,WinSettings); return false; } </script> <asp:GridView ID="gvView" runat="server" PagerSettings-Position="TopAndBottom" AutoGenerateColumns="False" AllowPaging="True" AllowSorting="True" OnPageIndexChanging="gvView_PageIndexChanging" OnSorting="gvView_Sorting" OnRowDataBound="gvView_RowDataBound" HeaderStyle-CssClass="GridTableHeader" AlternatingRowStyle-CssClass="GridTableCellsAlt" RowStyle-CssClass="GridTableCells" > <PagerStyle HorizontalAlign="left" /> <Columns> <asp:TemplateField HeaderStyle-CssClass="GridTableHeader" > <ItemTemplate > <asp:Button ID="btnViewDetails" Text="ViewDetails" runat="server" /> </ItemTemplate> <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" /> <HeaderStyle Font-Size="Small" /> </asp:TemplateField> <asp:BoundField DataField="EmpId" HeaderText="EmpID" SortExpression="EmpId" /> <asp:BoundField DataField="EmpName" HeaderText="EmpName" SortExpression="EmpName" /> </Columns> </asp:GridView>
You can control the button's visible or invisible property from your .cs page.
E.g. Consider the following scenario. The datagrid needs to be
populated with the employee details populated from the dataset.
The condition is if the user belongs to Admin group, ViewDetails
button should be visible so that by clicking the button user will be
able to view the details in the new window.
The dataset contains a column called "Admin" which holds
either 0 or 1. Button should be visible for the rows which has Admin value as 1 .
For the above requirement code should be written like this
/// Binds the datagrid rows items protected void gvView_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { Button btnViewDetails = (Button)e.Row.FindControl ("btnViewDetails"); if( Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Admin")) == 1) { //Add an attribute to the button ViewDetails btnViewDetails.Attributes.Add("onclick", "return OpenDetailsPage('" + DataBinder.Eval(e.Row.DataItem, "EmpID") + "')"); } else { btnViewDetails.Visible = false; } } }
Onclicking the button the method will call a javascript function to open a new window.