With the advent of SharePoint 2010 and Visual Studio 2010, new Visual Studio Tools are now available to help you the developer to build solutions using SharePoint 2010 easily. In this post we will look at one of the simplest yet long awaited features to come to the developers. The new feature is having the ability to create a Visual Web Part.
So to begin I am using Windows Foundation Services 2010 (Or what was known as WSS 4) and Visual Studio 2010 with the SharePoint Tools installed.
Let's begin open up Visual Studio 2010 and create a project based on the Visual Web Part Template:
You then need to specify the instance of SharePoint that you are using:
Now let's look at the structure of the project:
You will notice that the project now comes with all the components needed to create this web part.
- Feature Definition
- WSP Package Definition
- Web Part Code
- User Control Code (Visual Elements)
For this example we will simply create the web part, in another post we will look at the other items. So now open the file called "VisualWebPart1UserControl.ascx" or whatever you called yours. Using the standard ASP.NET controls add a label and then a button to the page in whatever layout you wish to use.
If we now double click the button we should be presented with the following code:
We are going to modify the code slightly to the following. Notice also that the intellisense features work really well for this:
Now we have our web part if we now open up the file "VisualWebPart1.cs" we can see what a Visual Web Part is actually made of and how it is called.
Notice how we are calling a user control that will be stored within the CONTROLTEMPLATE of the server. So let's look at our web part in action. Firstly select the build menu and choose to build the deploy the solution.
This process will deploy the web part to the site collection you specified when the project was created, for me it is http://wss4. So once it has deployed I am going to edit my page and choose to add a web part:
I am going to select my new web part that is now listed within the custom category:
I can choose to add this web part to the page now and it should render like this:
Now if I run the page as normal and press the button my web part should now update.
So if we now check, the solution package that was created has deployed everything my web part needed but more importantly create a feature that is activated as part of the deploy process:
This is a great and powerful feature of Visual Studio 2010, SharePoint Tools and SharePoint 2010.