i had a small requirement to sort a grid column when column header is clicked .
Here is what i did
a) Enable allowsorting Property in grid-view
add Property SortExpression
b) Create a Property for sort direction and store in a view state
public SortDirection dir
{
get
{
if (ViewState["dirState"] == null)
{
ViewState["dirState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirState"];
}
set
{
ViewState["dirState"] = value;
}
}
c) if data is stored in dataset copy dataset to datatable
dt = dsshowTen.Tables[0];
d) add event GridView1_Sorting(object sender, GridViewSortEventArgs e) event
the above 2 screenshot shows sorted records of Tenant_Name column
Here is what i did
a) Enable allowsorting Property in grid-view
<asp:GridView ID="GridView1"
runat="server"
CellPadding="3"
GridLines="Horizontal"
Font-Names="Verdana" Font-Size="10" DataKeyNames="Tenant_Name"
AutoGenerateColumns="false" AllowSorting="true"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowcreated="GridView1_RowCreated"
onrowediting="GridView1_RowEditing"
onrowupdated="GridView1_RowUpdated" onrowupdating="GridView1_RowUpdating"
onrowdeleted="GridView1_RowDeleted" onrowdeleting="GridView1_RowDeleting"
onrowdatabound="GridView1_RowDataBound" onsorting="GridView1_Sorting"
>
add Property SortExpression
<asp:BoundField DataField="Tenant_Name" HeaderText="Tenant Name" ReadOnly="true" SortExpression="Tenant_Name" />
b) Create a Property for sort direction and store in a view state
public SortDirection dir
{
get
{
if (ViewState["dirState"] == null)
{
ViewState["dirState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirState"];
}
set
{
ViewState["dirState"] = value;
}
}
c) if data is stored in dataset copy dataset to datatable
dt = dsshowTen.Tables[0];
d) add event GridView1_Sorting(object sender, GridViewSortEventArgs e) event
string
sortingDirection = string.Empty;
if (dir
== SortDirection.Ascending)
{
dir = SortDirection.Descending;
sortingDirection = "Desc";
}
else
{
dir = SortDirection.Ascending;
sortingDirection = "Asc";
}
DataView
sortedView = new DataView(dt);
sortedView.Sort = e.SortExpression + " " + sortingDirection;
GridView1.DataSource = sortedView;
GridView1.DataBind();
No comments:
Post a Comment