Grid View sorting

Create a grid view
To enable sorting we have to set the AllowSorting to True and add event to handle OnSorting event.

<asp:GridView ID="GridView1" runat="server" AllowSorting="True" OnSorting="GridView1_Sorting" >
</asp:GridView>

In the code behind
We have to maintain the sort expression i.e. the column to the sorted on and also the direction i.e. ascending or descending. I have used View State to maintain these. We can also use session variable to maintain these. In the page load we set the initial sort expression and the initial sort order.

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//setting the initial sort expression and sort order
DataView dv = getData("odbcName asc");
//storing the initial sort expression and the initial sort order
ViewState["sortExpression"] = "odbcName";
ViewState["sortDirection"] = "asc";
GridView1.DataSource = dv;
GridView1.DataBind();
}
}

//function to get the data in sorted order
private DataView getData(string sortExpression)
{
DataBaseConnectivity db = new DataBaseConnectivity();
string connectionString = db.getConnectionString();
OleDbConnection conn = null;
DataView dv = null;

try
{
conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "dbo.ebt_getByPipe_ebbDataBases";
cmd.Parameters.AddWithValue("@pipeLineGroup", PipelineCodesDDL.SelectedValue);
OleDbDataAdapter oda = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
oda.Fill(ds);
ds.CaseSensitive = false;
dv = new DataView(ds.Tables[0]);
dv.Sort = sortExpression;
}
catch (OleDbException ex)
{
dv = null;
string errMessage = ex.Message;
errMessage = errMessage.Replace("\n", " ");
Response.Redirect("~/error.aspx?errCode=" + ex.ErrorCode + "&errDesc=" + errMessage);
}
finally
{
if (conn != null)
conn.Close();
}
return dv;
}


protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortDirection = ViewState["sortDirection"].ToString();
string sortExpression = ViewState["sortExpression"].ToString();
if (sortExpression != e.SortExpression)//new link is clicked
{
sortDirection = "asc";
sortExpression = e.SortExpression;
}
else// if already selected link is clicked
{
if (sortDirection == "asc")
sortDirection = "desc";
else
sortDirection = "asc";
}
ViewState["sortExpression"] = sortExpression;
ViewState["sortDirection"] = sortDirection;
DataView dv = getData(sortExpression + " " + sortDirection);
GridView1.DataSource = dv;
GridView1.DataBind();
}