August 13, 2012

Filtering in Sp gridview


#region Sorting
        protected void grdAnnDetails_Sorting(object sender, GridViewSortEventArgs e)
        {
            hidecontrl();                                 

            DataTable dt = Session["All"] as DataTable;
            if (dt != null)
            {
                dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);

            }

        }
        #endregion
        #region SortDirection
        private string GetSortDirection(string column)
        {
            string sortDirection = "ASC";
            string sortExpression = ViewState["SortExpression"] as string;

            if (sortExpression != null)
            {
                if (sortExpression == column)
                {
                    string lastDirection = ViewState["SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }
            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }
        #endregion
        #region Filtering
        protected override void OnPreRender(EventArgs e)
        {
            try
            {
                hidecontrl();
                buildFilterView(ObjD.FilterExpression);
            }
            catch (Exception ex)
            {
                ErrorHelper.Add(Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace));
                SPUtility.TransferToErrorPage(MessageHelper.Message(MessageMode.CommonErrorMessage));
            }
        }

        void buildFilterView(string filterExp)
        {
            string lastExp = filterExp;
            if (lastExp.Contains("AND"))
            {
                if (lastExp.Length < lastExp.LastIndexOf("AND") + 4)
                { lastExp = lastExp.Substring(lastExp.LastIndexOf("AND") + 4); }
                else
                { lastExp = string.Empty; }
            }

            //update the filter
            if (!string.IsNullOrEmpty(lastExp))
            { FilterExpression = lastExp; }

            //reset object dataset filter
            if (!string.IsNullOrEmpty(FilterExpression))
            { ObjD.FilterExpression = FilterExpression; }
        }



        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);

            if (Context.Request.Form["__EVENTARGUMENT"] != null &&
                 Context.Request.Form["__EVENTARGUMENT"].Contains("__ClearFilter__"))
            {
                ViewState.Remove("FilterExpression");
            }
        }

        string FilterExpression
        {
            get
            {
                if (ViewState["FilterExpression"] == null)
                { ViewState["FilterExpression"] = ""; }

                return (string)ViewState["FilterExpression"];
            }
            set
            {
                string thisFilterExpression = "(" + value.ToString() + ")";
                List<string> fullFilterExpression = new List<string>();

                if (ViewState["FilterExpression"] != null)
                {
                    string[] fullFilterExp = ViewState["FilterExpression"].ToString().Split(_ssep, StringSplitOptions.RemoveEmptyEntries);
                    fullFilterExpression.AddRange(fullFilterExp);

                    int index = fullFilterExpression.FindIndex(s => s.Contains(thisFilterExpression));
                    if (index == -1)
                    { fullFilterExpression.Add(thisFilterExpression); }
                }
                else
                {
                    fullFilterExpression.Add(thisFilterExpression);
                }
                string filterExp = string.Empty;
                fullFilterExpression.ForEach(s => filterExp += s + " AND ");
                filterExp = filterExp.Remove(filterExp.LastIndexOf(" AND "));
                if (!filterExp.EndsWith("))") && filterExp.Contains("AND"))
                { filterExp = "(" + filterExp + ")"; }
                ViewState["FilterExpression"] = filterExp;
            }
        }
        public void AssignData()
        {

            ObjD = new ObjectDataSource();
            ObjD.ID = "gridds";
            ObjD.SelectMethod = "GetData";
            ObjD.FilterExpression = FilterExpression;
            ObjD.TypeName = this.GetType().AssemblyQualifiedName;
            ObjD.ObjectCreating += new ObjectDataSourceObjectEventHandler(ObjD_ObjectCreating);
            this.Controls.Add(ObjD);
            grdAnnouAll.DataSourceID = ObjD.ID;          
            ObjD.Filtering += new ObjectDataSourceFilteringEventHandler(ObjD_Filtering);          
        }


        public DataTable GetData()
        {
            DataTable dt = new DataTable();

            if (ViewState["Dboard"] == null)
            {
               
                if (!string.IsNullOrEmpty(Request.QueryString["Annmoreid"]))
                {
                    if (!string.IsNullOrEmpty(EncryptHelper.DecryptText(Request.QueryString["Annmoreid "])))
                    {

                        AnnouncementBL obj = new AnnouncementBL(Convert.ToInt32((EncryptHelper.DecryptText(Request.QueryString["Annmoreid "]))));

                        if (IsSuperAdmin || IsAdmin || IsManager)
                        {
                            ViewState["Dboard"] = obj.GetAllItems();

                        }
                        else
                        {

                            ViewState["Dboard"] = obj.GetDispalyedListItem();

                        }
                    }
                    else
                    {
                        Response.Redirect("/Pages/Hme.aspx", false);
                    }

                }
                else
                {
                    AnnouncementBL allobj = new AnnouncementBL();
                    ViewState["Dboard"] = allobj.GetAllListItem();
                }
            }           
           
             dt = (DataTable)ViewState["Dboard"];
            return dt;        


        }


        void ObjD_Filtering(object sender, ObjectDataSourceFilteringEventArgs e)
        {
            ViewState["FilterExpression"] = ((ObjectDataSourceView)sender).FilterExpression;
        }

        void ObjD_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            e.ObjectInstance = this;
        }




        #endregion
 Assigndata should be called in Pageload

Paging in SP Gridview




        protected void grd_ClickNext(Object sender, EventArgs e)
        {
            try
            {
                grd.DataSourceID = ObjD.ID;

            }
            catch (Exception ex)
            {
                ErrorHelper.Add(Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace));
                SPUtility.TransferToErrorPage(MessageHelper.Message(MessageMode.CommonErrorMessage));
            }
        }
        protected void grd_ClickPrevious(Object sender, EventArgs e)
        {
            try
            {
                grd.DataSourceID = ObjD.ID;

            }
            catch (Exception ex)
            {
                ErrorHelper.Add(Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace));
                SPUtility.TransferToErrorPage(MessageHelper.Message(MessageMode.CommonErrorMessage));
            }
        }
        protected void grd_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                grd.PageIndex = e.NewPageIndex;


            }
            catch (Exception ex)
            {
                ErrorHelper.Add(Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace));
                SPUtility.TransferToErrorPage(MessageHelper.Message(MessageMode.CommonErrorMessage));
            }
        }
      

Server side script for Hiding controls




 public void hidecontrl()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<script type=\"text/javascript\">\n");
            sb.Append("Sys.Application.add_load(hidebtn);\n");
            sb.Append("function hidebtn() {\n");
            sb.Append("$('input:imagebutton[id$=imgbtnAnnouncEdit]').hide();\n");
            sb.Append("$('input:imagebutton[id$=imgbtnAnnouncDelete]').hide();}\n");
            sb.Append("</script>\n");
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "Startup", sb.ToString());      
        }
      

call hidecontrl(); in whichever function you need.