Sunday, February 16, 2014

SharePoint Search Programmatically

SharePoint Search Programmatically Below code snippet will helps you to understand how the SharePoint search can be done via code Of this will be useful along with your custom application in WebPart or SharePoint application Page. Here,I have one text box where query string or keyword will be typed and hit the search button.Search result will be displayed in the GridView.
 protected void SearchQuery(object sender, EventArgs e)
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                KeywordQuery searchText = new KeywordQuery(site);
                searchText.ResultsProvider = SearchProvider.Default;
                searchText.QueryText = txtSearch.Text;
                searchText.ResultTypes |= ResultType.RelevantResults;
                ResultTableCollection resultTableCols = searchText.Execute();
                if (resultTableCols.Exists(ResultType.RelevantResults))
                    ResultTable searchResult = resultTableCols[ResultType.RelevantResults];
                    DataTable dt = new DataTable();
                    dt.Load(searchResult, LoadOption.OverwriteChanges);
                    grdView.DataSource = dt;

                    grdView.EmptyDataText = " No result found !";

SharePoint 2010 Search Programmatically