Usually you can able to sort a grid view by clicking the header of the grid. If you want to sort the grid view dynamically, without changing the store procedure of the binding object, the following code will help.
The SortGridView() function will accept the field name and Sorting type ‘ Asc’ or ‘ DESC’. Grid displays the SalesReasonName in Desceding Order.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SortGridView("SalesReasonName", " DESC");
}
}
static string sortExpression;
private void SortGridView(string sortExpression, string direction)
{
SqlConnection con;
con = new SqlConnection("server=;uid=sa;password=;database=AdventureWorksDW");
con.Open();
SqlDataAdapter oAdapter = new SqlDataAdapter("SalesReason_S", con);
oAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet oDataSet = new DataSet();
oAdapter.Fill(oDataSet);
DataTable dt = oDataSet.Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
}