How to add sorting to gridview based on any columns?

Posted by Vijetha under C# on 3/16/2012 | Points: 10 | Views : 3163 | Status : [Member] | Replies : 2
Hi,
I do have a gridview with 5 columns,but how do i add the sorting based on any particular column like customercode or name etc.

Regards,
Vijetha.M.M




Responses

Posted by: Vforvijay on: 3/16/2012 [Member] Starter | Points: 25

Up
0
Down
hi.
Refer the below link..for sorting
http://www.dotnetcode.in/2012/02/apply-sorting-in-gridview-using-aspnet.html


Vijetha, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sksamantaray on: 3/16/2012 [Member] Silver | Points: 25

Up
0
Down
Hi Vijeta,
First of all you need to use OnSorting="SortRecords" in Gridview.
Then follow these steps:
   protected void SortRecords(object sender, GridViewSortEventArgs e)

{
DataTable dataTable = GridDataSource();

if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = GetSortExpression(e);
grdBlock.DataSource = dataView;
grdBlock.DataBind();
}
}

private string GetSortExpression(GridViewSortEventArgs e)
{
string sortDirection = string.Empty;
// if clicked on the same column twice then let it toggle the sort order, else reset to ascending
if (ViewState["SortExpression"] != null)
{
if (!ViewState["SortExpression"].ToString().Equals(e.SortExpression.ToLower()))
{
ViewState["SortDirection"] = null;
}
}

if (ViewState["SortDirection"] != null)
{
if (ViewState["SortDirection"].ToString().Equals("ASC"))
{
sortDirection = "DESC";
ViewState["SortDirection"] = "DESC";
}
else
{
sortDirection = "ASC";
ViewState["SortDirection"] = "ASC";
}
}
else
{
ViewState["SortDirection"] = "ASC";
}
ViewState["SortExpression"] = e.SortExpression.ToLower();

return e.SortExpression + " " + sortDirection;
}

protected DataTable GridDataSource()
{
DataTable dTable = new DataTable();
DataAccessClass dao = new DataAccessClass();
DataSet ds = new DataSet();
try
{
SqlParameter Blockname = new SqlParameter("@Blockname", null);
SqlParameter[] DBblock = new SqlParameter[1] { Blockname };
ds = dao.ExecuteSelect("spGetBlockData", DBblock);
dTable = ds.Tables[0];

}
catch (Exception ex)
{

}
finally
{
ds.Dispose();

}
return dTable;
}


Thanks,
Sanjay

Vijetha, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response