May 2010

Sort on Gridview

Default.aspx.cs page:

Delcare Object
DAL objDal = new DAL();
string SORT_DESC = “Desc”;
string SORT_ASC = “Asc”;

Page Load Event
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindCountryGrid();

if (!String.IsNullOrEmpty(Request.QueryString[“Result”]))
{
DisplayMessage();
}
}
}

Bind Grid Code

private void BindCountryGrid()
{
DataTable dtCountry = new DataTable();
dtCountry = objDal.GetDataTable(“spGetCountry”);
if (dtCountry != null)
{
if (dtCountry.Rows.Count > 0)
{
dgCountry.DataSource = dtCountry;
dgCountry.DataBind();
ViewState[“dtCountry”] = dtCountry;
}
}
}

Sort the data of Gridview

protected void dgCountry_Sorting(object sender, GridViewSortEventArgs e)
{
if (ViewState[“sortMode”] == null)
{
ViewState[“sortMode”] = SORT_DESC;
}
if (ViewState[“sortMode”] != null)
{
if (Convert.ToString(ViewState[“sortMode”]).Trim().Equals(SORT_ASC))
{
ViewState[“sortMode”] = SORT_DESC;
}
else
{
ViewState[“sortMode”] = SORT_ASC;
}
}

string sortexpr = e.SortExpression;

DataView dvProd = default(DataView);
DataTable dtProd = new DataTable();
dtProd = (DataTable)ViewState[“dtCountry”];

if ((dtProd != null))
{
if (dtProd.Rows.Count > 0)
{
dvProd = dtProd.DefaultView;
dvProd.Sort = sortexpr.Trim() + ” ” + ViewState[“sortMode”];
dgCountry.DataSource = dvProd;
dgCountry.DataBind();
}
}
}

Note : You have to sorting property true of gridview on aspx page.