In this post I wil create a simple custom Web Part in Visual Studio 2010 for SharePoint 2010. First we choose a Empty SharePoint Project where we later add a Visual Web Part.
Image may be NSFW.
Clik here to view.
This new Visual Web Part includes a number of files. Such as the .cs file where you can add functionality. For this example let’s ad some simple code:
[ToolboxItemAttribute(false)] public class CustomWebpart : WebPart { protected override void RenderContents(HtmlTextWriter writer) { writer.WriteLine("Some text"); } }
Now we have some functionality in our .cs file:
Image may be NSFW.
Clik here to view.
A other file that is created when adding a Visual Web Part is the Element.xml. This file will define the Web Part to SharePoint
<?xml version="1.0" encoding="utf-8"?> <Elements xmlns="http://schemas.microsoft.com/sharepoint/" > <Module Name="CustomWebpart" List="113" Url="_catalogs/wp"> <File Path="CustomWebpart\CustomWebpart.webpart" Url="CustomWebpart.webpart" Type="GhostableInLibrary"> <Property Name="Group" Value="Custom" /> </File> </Module> </Elements> <div>
The last file I will discuss is the .webpart file. This is an XML file that provides initial configuration to the webpart. Such as the Title and Discription.
Image may be NSFW.
Clik here to view.
An important aspect is that you are sure that the project is connected to your SharePoint (in this case) sitecollection. You can check the connection in the server explorer. In the following image you can see that I have a connection with my local SharePoint sitecollection and that I can even show all kind of information about my sitecollection:
Image may be NSFW.
Clik here to view.
The only thing we have to do now is to build and deploy the solution to the SharePoint environment. We can do this by deploying it to the site: Build > Deploy Solution.
After deploying the solution go to your SharePoint site and edit the desired page. When we now take a look at the webpart gallery, we see that the Web Part is added to the custom webpart group:
Image may be NSFW.
Clik here to view.
Just select the Web Part and click the Add button. We now have our custom Visual Web Part in our SharePoint environment!