Sunday, May 11, 2008

A Simple Search Web Part

This web part will simply implement a search function by redirecting the user to the out-of-box sharepoint search result page.

Steps:
1. Add a web custom control to the solution, name it SearchWebPart.cs.
2. Add the following namespaces:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Linq;

using System.Text;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

3. Change the inheritance from WebControl to WebPart and delete the default Text property. Also get rid of the all the default attributes on the SearchWebPart class.

namespace SearchWebPart

{

public class SearchWebPart : WebPart

{

Label lblSearch = null;

TextBox txtSearch = null;

Button btnSearch = null;

4. Add the search textbox and search button.

protected override void CreateChildControls()

{

btnSearch = new Button();

btnSearch.Width = new Unit(50, UnitType.Pixel);

btnSearch.Text = "Search";

btnSearch.Click += new EventHandler(btnSearch_Click);

Controls.Add(btnSearch);

lblSearch = new Label();

lblSearch.Text = "Search: ";

Controls.Add(lblSearch);

txtSearch = new TextBox();

txtSearch.Width = new Unit(295, UnitType.Pixel);

Controls.Add(txtSearch);

}

5. Redirect user to the sharepoint out-of-box search result page of publishing portal and specify the Newsletters scope.

void btnSearch_Click(object sender, EventArgs e)

{

Page.Response.Redirect(string.Format(@"/Search/results.aspx?k={0}&s=Newsletters", HttpUtility.UrlEncode(txtSearch.Text)));

}

protected override void RenderContents(HtmlTextWriter output)

{

output.Write(@"<div style='width:600px; display:block; overflow:visible;' id='DIV1'>");

lblSearch.RenderControl(output);

output.Write(@"&nbsp;");

txtSearch.RenderControl(output);

btnSearch.RenderControl(output);

output.Write(@"</div>");

}

}

}

6. Add the dll to the GAC, add the safecontrol to the web.config.

7. Go to Site Settings > Web Parts > New > tick the webpart and click Populate Gallery.

8. Add the web part to the page.

blog comments powered by Disqus