views:

19

answers:

2

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:GridView>   

  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)
    {
   ...
    }
A: 

DataTable tab = DataGrid.DataSource as DataTable; tab.DefaultView.Sort = columnName + " " + sortOrder; tab = tab.DefaultView.ToTable();

//tab here will be sorted

KhanZeeshan
Thanks ! This sorts for one column. What if i need to give a windows like functionality? What do i need to do?
deepa
it'll sort one column but whole grid will be sorted on the basis of that column. like in Details View in Explorer.
KhanZeeshan
KhanZeeshan
A: 

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();
KMan
Thanks. Works great !
deepa