Saturday, 30 March 2013

asp.net grid view sorting in linq to sql



  public void bindGrid()
    {
        REGISTRATIONDataContext objDB = new REGISTRATIONDataContext();
        var listuser = (from p in objDB.REGISTRATIONs
                       select p).ToArray();
       
        if (listuser != null)
        {
            if (GridViewSortDirection == SortDirection.Ascending)
            {
                GridView1.DataSource = listuser.OrderBy(x => x.GetType().GetProperty(GridViewSortExpression).GetValue(x, null)).ToList();
            }
            else
            {
                GridView1.DataSource = listuser.OrderByDescending(x => x.GetType().GetProperty(GridViewSortExpression).GetValue(x, null)).ToList();
            };
        }
        else
        {
            GridView1.DataSource = null;
        }
        //GridView1.DataSource = listuser;
        GridView1.DataBind();
    }



 public string GridViewSortExpression
    {
        get
        {
          return ViewState["GridViewSortExpression"] == null ? "NAME":ViewState["GridViewSortExpression"] as string;    
        }
        set
        {
            ViewState["GridViewSortExpression"] = value;
        }
    }

    public SortDirection GridViewSortDirection
    {
        get
        {
            if (ViewState["sortDirection"] == null)
                ViewState["sortDirection"] = SortDirection.Ascending;

            return (SortDirection)ViewState["sortDirection"];
        }
        set { ViewState["sortDirection"] = value; }
    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {

        GridViewSortExpression = e.SortExpression;
        if (GridViewSortDirection == SortDirection.Ascending)
        {
            GridViewSortDirection = SortDirection.Descending;
        }
        else
        {
            GridViewSortDirection = SortDirection.Ascending;
        };
        bindGrid();  
    }

No comments:

Post a Comment