Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Code Sample: Custom Keyword Search Web Part Code
Collapse the table of content
Expand the table of content

Code Sample: Custom Keyword Search Web Part Code

Last modified: April 19, 2010

Applies to: SharePoint Server 2010

The following is the complete sample code for the Custom Keyword Search Web Part, described in Walkthrough: Creating a Basic Search Web Part Using the Query Object Model.

using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.Office.Server.Search.Query;
using Microsoft.Office.Server.Search.Administration;
using System.Data;

namespace CustomKeywordSearch.Custom_Keyword_Search
    public class Custom_Keyword_Search : WebPart
        Button queryButton;
        TextBox queryTextBox;
        Label resultsLabel;
        DataGrid resultsGrid;

        protected override void CreateChildControls()
            queryTextBox = new TextBox();
            queryButton = new Button();
            queryButton.Text = "Start Search";
            queryButton.Click += new EventHandler(queryButton_Click);
            resultsLabel = new Label();

        void ExecuteKeywordQuery(string queryText)
            SearchServiceApplicationProxy proxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy
            KeywordQuery query = new KeywordQuery(proxy);
            query.ResultsProvider = Microsoft.Office.Server.Search.Query.SearchProvider.Default;
            query.QueryText = queryText;
            query.ResultTypes |= ResultType.RelevantResults;
            ResultTableCollection searchResults = query.Execute();
            if (searchResults.Exists(ResultType.RelevantResults))
                ResultTable searchResult = searchResults[ResultType.RelevantResults];
                DataTable result = new DataTable();
                result.TableName = "Result";
                result.Load(searchResult, LoadOption.OverwriteChanges);


        private void FillResultsGrid(DataTable resultTable)
            //Instantiate the DataGrid
            resultsGrid = new DataGrid();
            //Set the DataSource
            resultsGrid.DataSource = resultTable;
            //Bind the data to the DataGrid
            //Add the DataGrid to the controls

        void queryButton_Click(object sender, EventArgs e)
            if (queryTextBox.Text != string.Empty)
                resultsLabel.Text = "You must enter a search word.";
© 2015 Microsoft