Code Sample: Custom Keyword Search Web Part Code
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
{
[ToolboxItemAttribute(false)]
public class Custom_Keyword_Search : WebPart
{
Button queryButton;
TextBox queryTextBox;
Label resultsLabel;
DataGrid resultsGrid;
protected override void CreateChildControls()
{
Controls.Clear();
queryTextBox = new TextBox();
this.Controls.Add(queryTextBox);
queryButton = new Button();
queryButton.Text = "Start Search";
queryButton.Click += new EventHandler(queryButton_Click);
this.Controls.Add(queryButton);
resultsLabel = new Label();
this.Controls.Add(resultsLabel);
}
void ExecuteKeywordQuery(string queryText)
{
SearchServiceApplicationProxy proxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy
(SPServiceContext.GetContext(SPContext.Current.Site));
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);
FillResultsGrid(result);
}
}
private void FillResultsGrid(DataTable resultTable)
{
//Instantiate the DataGrid
resultsGrid = new DataGrid();
//Set the DataSource
resultsGrid.DataSource = resultTable;
//Bind the data to the DataGrid
resultsGrid.DataBind();
//Add the DataGrid to the controls
Controls.Add(resultsGrid);
}
void queryButton_Click(object sender, EventArgs e)
{
if (queryTextBox.Text != string.Empty)
{
ExecuteKeywordQuery(queryTextBox.Text);
}
else
{
resultsLabel.Text = "You must enter a search word.";
}
}
}
}
See Also
Tasks
Walkthrough: Creating a Basic Search Web Part Using the Query Object Model
Reference
Microsoft.Office.Server.Search.Query
Concepts
Enterprise Search Query Architecture