1

I have created a custom Search Results page and need to add the Search Box webpart and Search Results webpart to the page programmatically. Has anyone ever accomplished this before?

1

Use the Web Part Manager class, either SPWebPartManager or SPLimitedWebPartManager. There are a ton of blog posts that explain how to do this in PowerShell and as part of Feature Deployment.

  • I've used this class to accomplish adding CEWP and LVWP/CQWP's on the page. I think it was a little different to add Search webparts. I did figure out how to do this. I ended up referencing the classes "Microsoft.Office.Server.Search" and "Microsoft.Office.Server.Search.WebControls" then was able to access the Search Results and Search Box as webparts and add them successfully to the page – nholloway4 Apr 8 '14 at 15:03
  • Are you missing a feature dependency? If you browse to the site can you see the web parts in the gallery? – Matthew McDermott Apr 8 '14 at 22:41
  • I wasn't missing a feature dependency. Yes, I can see the web parts in the gallery. I will post a snippet of the code later – nholloway4 Apr 9 '14 at 12:50
  • A gogle-doesn't-hurt-like answer, very helpful. – Szybki Dec 13 '17 at 7:04
1

Here is a snippet of the code I used

using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls.WebParts;
using Microsoft.Office.Server.Search;
using Microsoft.Office.Server.Search.WebControls;



     private static void SetupSearch( SPSite site)
     {
        try
        {
            MyUtil.createPage(site, "/", "Minimal.Search.aspx" , "SearchResults.aspx" , "Search Results" );
            SearchBoxScriptWebPart searchBox = new SearchBoxScriptWebPart ();
            ResultScriptWebPart resultsParts = new ResultScriptWebPart ();
            site.RootWeb.AddWebPartToPage( "Pages", "SearchResults.aspx" , "RightColumn", 0, true , searchBox, PartChromeType.None);
            site.RootWeb.AddWebPartToPage( "Pages", "SearchResults.aspx" , "RightColumn", 1, false , resultsParts, PartChromeType.None);


            foreach ( SPWeb oWeb in site.AllWebs)
            {
                oWeb.AllProperties[ "SRCH_SB_SET_SITE"] = "{\"Inherit\":false,\"ResultsPageAddress\":\"~sitecollection/Pages/SearchResults.aspx\",\"ShowNavigation\":false}" ;
                oWeb.Update();
            }
        }
        catch ( Exception ex)
        {
            Logging.LogError( "Error: MyLoggingError for Search " + ex.Message);
        }


     }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.