Tuesday, April 26, 2011

sorting in gridview

protected void BindProductsGrid()
{
DataTable dt =GetAllProducts();
if (dt.Rows.Count > 0)
{
if (ViewState["Sort"] == null)
dt.DefaultView.Sort = "ProductName Asc";
else
dt.DefaultView.Sort = ViewState["Sort"].ToString();

gvProducts.AllowSorting = true;
gvProducts.DataSource = dt.DefaultView;
gvProducts.DataBind();
}
else
{
gvProducts.AllowSorting = false;
DataSetLinqOperators.ShowNoResultFound(dt, gvProducts, "There is no Product Types.");
}
}
public static DataTable GetAllProducts()
{
bhscEntities ese = new bhscEntities();
var pt = (from c in ese.Products
join d in ese.ProductImages on c.ProductId equals d.ProductId
where c.Deleted == false
orderby c.ProductName ascending
select new
{
c.ProductId,
d.Thumbnail,
c.ProductName,
c.ProductOption1Value,
c.ProductOption2Value,
c.ProductOption3Value,
c.SKU,
c.Saleprice
});

DataTable dt = DataSetLinqOperators.CopyToDataTable(pt);
return dt;
}

protected void gvProducts_Sorting(object sender, GridViewSortEventArgs e)
{
if (ViewState["Sort"] != null)
{
if (ViewState["Sort"].ToString().Substring(ViewState["Sort"].ToString().Length - 4, 4).Trim() == "ASC")
ViewState["Sort"] = e.SortExpression + " DESC";
else
ViewState["Sort"] = e.SortExpression + " ASC";
}
else
ViewState["Sort"] = e.SortExpression.ToString() + " Desc";

BindProductsGrid();
}

No comments:

Post a Comment