Archive

Posts Tagged ‘Sharepoint development’

Enable Full Toolbar on an XSLT List View Web Part (XsltListViewWebPart) / on a list

July 9, 2012 3 comments

Enabling toolbar for a list programmatically means to enable it on xslt list view web part..Here’s the code:

private void EnableToolbarOnXsltListViewWP(string viewName, string listName, string webUrl)
        {
            using (var spSite = new SPSite(webUrl))
            {
                using (SPWeb web = spSite.OpenWeb())
                {
                    spSite.AllowUnsafeUpdates = true;
                    web.AllowUnsafeUpdates = true;
                    SPList spList = web.Lists[listName];
                    SPView spView = spList.Views[viewName];
                    SPLimitedWebPartManager spLimitedWebPartManager = web.GetLimitedWebPartManager(spView.Url, PersonalizationScope.Shared);
                    foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in spLimitedWebPartManager.WebParts)
                    {
                        if (webPart.GetType().Name.Equals("XsltListViewWebPart") && webPart.Title == Config.ListName_MyCVs)
                        {
                            try
                            {
                                MethodInfo ensureViewMethod = webPart.GetType().GetMethod("EnsureView", BindingFlags.Instance | BindingFlags.NonPublic);
                                object[] ensureViewParams = { };
                                ensureViewMethod.Invoke(webPart, ensureViewParams);
                                FieldInfo viewFieldInfo = webPart.GetType().GetField("view", BindingFlags.NonPublic | BindingFlags.Instance);
                                var view = viewFieldInfo.GetValue(webPart) as SPView;
                                Type[] toolbarMethodParamTypes = { Type.GetType("System.String") };
                                MethodInfo setToolbarTypeMethod = view.GetType().GetMethod("SetToolbarType", BindingFlags.Instance | BindingFlags.NonPublic, null, toolbarMethodParamTypes, null);
                                object[] setToolbarParam = { "ShowToolbar" };
                                setToolbarTypeMethod.Invoke(view, setToolbarParam);
                                view.Update();
                            }
                            catch (Exception ex)
                            {
                                Log.LogError("MyProjName", ex);
                            }
                        }
                    }
                    spSite.AllowUnsafeUpdates = false;
                }
            }
        }

Hope this helps-
Rehman.