priyanka.bangalore priyanka.bangalore - 11 months ago 43
ASP.NET (C#) Question

Sorting in GridView +

What should I do to perform the sorting in grid view?

Please help

Answer Source

You can implement code like the following:

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
     DataTable dataTable = GridView1.DataSource as DataTable;

     if (dataTable != null)
          DataView dataView = new DataView(dataTable);
          dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

          GridView1.DataSource = dataView;

private string ConvertSortDirectionToSql(SortDirection sortDirection)
     string newSortDirection = String.Empty;

     switch (sortDirection)
          case SortDirection.Ascending:
              newSortDirection = "ASC";

          case SortDirection.Descending:
              newSortDirection = "DESC";

     return newSortDirection;

With this code, your GridView definition should read:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowSorting="true" OnSorting="GridView1_Sorting">
    <asp:BoundField DataField="Name" HeaderText="People Names" SortExpression="Name" />
    <asp:BoundField DataField="Age" HeaderText="People Ages" SortExpression="Age" />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download