Sort the asp.net gridview on a bound column in the aspx page
I need to sort the rows in the asp:gridView in the aspx page on a field named LastName.
I bind the grid using a datatable in C#. I do not use the datasource in the aspx file.
Giving the SortExpression in the grid doesn't work.
Please can anyone direct me how to achieve this?
I've done this till now but it doesnt seem to sort
<asp:GridView ID="gdPlayersList" runat="server" AllowSorting="true"
AutoGenerateColumns="false" AlternatingRowStyle-BackColor="#F9F9F9"
Font-Size="X-Small" Font-Names="Verdana" Font-Bold="False"
DataKeyNames="PlayerId,CasinoId"
HeaderStyle-BorderWidth="1px" HeaderStyle-BackColor="LightGray"
HeaderStyle-BorderStyle="Solid" RowStyle-BorderColor="#666666"
RowStyle-BorderStyle="Solid" RowStyle-BorderWidth="1px"
RowStyle-ForeColor="#666666" OnRowDataBound="Grid_RowDataBound"
OnSorting="Grid_Onsorting"
EmptyDataText="No records found" >
<Columns>
<asp:BoundField HeaderText="First Name" DataField="FirstName" />
<asp:BoundField HeaderText="Last Name" DataField="LastName"
SortExpression="LastName"/>
<asp:BoundField HeaderText="Date opened" DataField="DateOpened"
DataFormatString="{0:mm/dd/YYYY}" HtmlEncode="false"
NullDisplayText="1/1/0001" />
</Columns>
</asp:GridVi开发者_运维问答ew>
C# code:
protected void Grid_Onsorting(object sender, GridViewSortEventArgs e)
{
DataTable sourceTable = gdPlayersList.DataSource as DataTable;
DataView view = new DataView(sourceTable);
view.Sort = e.SortExpression + " " + "DESC";
this.ViewState["sortExpression"] = e.SortExpression + " " + "DESC";
}
protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
...
}
Did you look into GridView.Sorting Event?
Handle the _Sorting
event, reassign and then DataBind()
.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
gv.DataSource = dt;
gv.DataBind();
DataTable tab = DataGrid.DataSource as DataTable;
tab.DefaultView.Sort = columnName + " " + sortOrder;
tab = tab.DefaultView.ToTable();
In the example above tab
will be sorted
精彩评论