Visual WebPart is one of the enhanced features of SPS 2010 which allows the developer to develop solution in a similar way the .aspx pages are developed. Once developed, VS 2010 allows us to directly deploy the solution in SharePoint environment. Compared to previous version it is no more different. Previously we need to explicitly create and load custom control in WebPart and by creating a feature or package we used to deploy the WebPart. In SPS 2010 all are taken care by VS 2010. When creating Visual WebPart VS2010 automatically adds the custom control and creates a package for you to deploy. Coooooooooooool!!!!!!!!!
Creating Visual WebPart using VS 2010
1. Create New Project using vs2010 and select Visual WebPart as shown in the below figure.
2. Enter Location to deploy WebPart. The solution will be deployed as a farm solution shown in the below figure.
3. Solution Explorer.
4. Rename VisualWebPart1 to UserWebPart or add new WebPart as shown below.
5. Code for UserWebPartUSerControl is shown below.
UserWebPartUserControl.ascx
UserWebPartUserControl.ascx.cs
using System;
using System.Web.UI;
using Microsoft.SharePoint;
namespace VisualWebPartDemo.UserWebPart
{
public partial class UserWebPartUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SPSite site = new SPSite(SPContext.Current.Site.ID);
SPWeb web = site.OpenWeb();
gvUsers.DataSource = web.SiteUsers;
gvUsers.DataBind();
}
}
}
}
6. Build and deploy the solution.
7. Once the solution is successfully deployed add WebPart on the page as show below.
WebPart displayin all the users from site.
Download sample code : http://www.sunilyadav.net/wp-content/uploads/VisualWebPartDemo.zip
Happy SharePointing!!