How to Create a Search Web Part in SharePoint 2010 Using Visual Studio

SharePoint 2010 has existed for a long time but there is still no end to the knowledge pertaining to it. So yes we will see how to create a Search Web Part in SharePoint 2010 using Visual Studio.

This is always a requirement in all our projects since users always want a certain search level with a single list rather than the entire site and it should filter respect to their fields. So for these requirements here is a Search Web part that can be easily modified depending on the user’s demand.

Let’s go for it.

Open your site and go to your list, like for me I have an Employee list with the following details as in the screenshot.

Now Open Visual Studio.

Create a new project.

Select Visual Web Part from the 2010 templates.

Connect your site with the webpart.

Once you click Ok you will see your project created as in the image below:

Click on VisualWebpart1UserControl.ascx.

Drag and drop the following label and text box as in the following screen:

Build it.

Now go to VisualWebPart1.cs.

In your solution add the following reference.

Microsoft.SharePoint

Microsoft.SharePoint.Client

Add the references as in the following to your cs page.

using System;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Data;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Client;

Now on the Search Button click paste the following code and I will explain what it is doing.

protectedvoid searchbtn_Click(object sender, EventArgs e)

{

//Initaily here I am clearing the grid view, if you don’t do it, results will keep on coming

GridView1.Columns.Clear();

// Calling My Web

SPWeb myweb = SPContext.Current.Web;

SPQuery qry = new SPQuery();

//Creating my Query as How we require for me I have two columns for data.