Friday, April 9, 2010

Creating custom properties in visual web part 2010



Visual webpart is one of best feature provided in Sharepoint 2010.This is the capability to create Webparts using a visual interface in Sharepoint 2010 so it’s called as Visual WebParts. it’s become very easy and fast to create webpart as well as deploy webpart to sharepoint server. Bringing visual webpart in visual studio 2010 microsoft had made it less effotable task. But there are some complicated things still developers need to know and one of that is creating custom properties. Few days back I worked on it for one the customer requirement. I think this could be very useful blog for those who are working on custom web part development using visual studio 2010.
When create new visual web part VS creates following files structure for a new visual web part

















It y creates the web part class and calls the user control by using page.LoadControl method. When we deploy the web part it copies the user control to the Control template folder under 14 hives and defies the same path in web part class.
The main thing we discus here is custom properties. The custom properties are written like this in user control class.
//properties for Title
[System.Web.UI.WebControls.WebParts.WebBrowsable(true),
System.Web.UI.WebControls.WebParts.WebDisplayName("WebPart Title"),
System.Web.UI.WebControls.WebParts.WebDescription(""),
System.Web.UI.WebControls.WebParts.Personalizable(
System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
System.ComponentModel.Category("Settings"),
System.ComponentModel.DefaultValue("")
]

public string WebpartTitle
{
get
{
return title;
}
set
{
title = value;
}
}
//propertiesfor Group Name
[System.Web.UI.WebControls.WebParts.WebBrowsable(true),
System.Web.UI.WebControls.WebParts.WebDisplayName("Group Name"),
System.Web.UI.WebControls.WebParts.WebDescription(""),
System.Web.UI.WebControls.WebParts.Personalizable(
System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
System.ComponentModel.Category("Settings"),
System.ComponentModel.DefaultValue("")
]
public string GroupName
{
get
{
return groupName;
}
set
{
groupName = value;
}
}

The same above mentioned code we need to write in web part class. In create child controls class we need to access the properties like this way
// Visual Studio might automatically update this path when you change the Visual Web Part project item.
private const string _ascxPath = @"~/_CONTROLTEMPLATES/SiteUsersWP/VisualWebPart1/VisualWebPart1UserControl.ascx";
protected override void CreateChildControls()
{
usercontrol = (VisualWebPart1UserControl)this.Page.LoadControl(_ascxPath);
usercontrol.WebpartTitle = this.WebpartTitle;
usercontrol.GroupName = this.GroupName;
Controls.Add(usercontrol);
base.CreateChildControls();

}

The custom properties we write goes under settings section when we edit web part in user interface.