Friday, June 27, 2014

SharePoint - Enable Filtering for Multiple SPGridView Control on same page

Hello Everyone, I have seen people implementing the SPGridView in their project/Webpart. When we try to use this webpart multiple times on same page the filtering does not work on multiple Grids correctly.
Let’s see how we can fix this.
The most essential part is referring aspgridview.js file in your control.



This js file helps us to run the Filter functionality.

The file has all the java script function which helps us to display the filtering actions. The ASPGrid view has one bug, if you try to add two SPGridView control on same page. The control starts misbehaving on filtering front. This happens since client id is not passed correctly to java script.
To resolve this I searched on net and found lot of people talking about the root cause of the problem and solution. But no one has solution which is generalized and will work for your grid filter column.
All the examples have shown how to fix it for individual column only.

-----------------------------------------------------------------------------

Here is code snippet which you need to add in your Web Part and call this method in Pre_Render method of your web part after binding grid view.

ColIndex refer to the index of the Column header which helps to apply filter menu.

protected void overrideFilterMenus(SPGridView SPGridViewObject)
        {
            int colIndex = 0;
            foreach (string strFilterColumn in SPGridViewObject.FilterDataFields.Split(','))
            {
                if (!string.IsNullOrEmpty(strFilterColumn))
                {
                    if (SPGridViewObject.HeaderRow.Controls[colIndex].Controls[0].GetType().Equals(typeof(Microsoft.SharePoint.WebControls.Menu)))
                    {
                        ((Microsoft.SharePoint.WebControls.Menu)SPGridViewObject.HeaderRow.Controls[colIndex].Controls[0]).ClientOnClickPreMenuOpen =
                          "SPGridView_FilterPreMenuOpen('" +
                          SPGridViewObject.ClientID + "','" + SPGridViewObject.ClientID +
                          "_SPGridViewFilterMenuTemplate', '%MENUCLIENTID%', '" + strFilterColumn + "', event);" +
                          " MMU_Open(byid('" + SPGridViewObject.ClientID + "_SPGridViewFilterMenuTemplate')," +
                          " MMU_GetMenuFromClientId('%MENUCLIENTID%'),event,true,null,0); return;";


                    }
                }
                colIndex++;
            }
        }