1/12/2012

How To Add Custom Web Part Properties To Visual Web Part In SharePoint 2010

Hey Folks,

Let's see how we can add custom web part properties to a visual web part in SharePoint 2010.

Open Visual Studio 2010 -> File -> New -> Project -> Visual C# -> SharePoint -> 2010 and select Visual Web Part project template as below:



In SharePoint Customization Wizard, validate the SharePoint 2010 site URL as below:



Once Visual Studio 2010 open ups, it will look like below:



Open VisualWebPart1.cs file and add below code:

 

namespace AddCustomProperty.VisualWebPart1
{
[ToolboxItemAttribute(false)]
public class VisualWebPart1 : WebPart
{
// Visual Studio might automatically update this path when you change the Visual Web Part project item.
private const string _ascxPath = @"~/_CONTROLTEMPLATES/AddCustomProperty/VisualWebPart1/VisualWebPart1UserControl.ascx";

private string _Name;
[WebBrowsable(true), WebDisplayName("Name"), WebDescription("My Name"),
Personalizable(PersonalizationScope.Shared), Category("Custom Property"),
System.ComponentModel.DefaultValue("")]

public string Name
{
get { return _Name; }
set { _Name = value; }
}

protected override void CreateChildControls()
{
VisualWebPart1UserControl control = (VisualWebPart1UserControl)Page.LoadControl(_ascxPath);
control.Name = Name;
Controls.Add(control);
}
}
}

 

It should look like below:



Open VisualWebPart1UserControl.ascx file and add below code:







It should look like below:



Open VisualWebPart1UserControl.ascx.cs file and add below code:



namespace AddCustomProperty.VisualWebPart1
{
public partial class VisualWebPart1UserControl : UserControl
{
public string Name { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
NameLiteral.Text = "Your Name is : " + this.Name;
}
}
}



It should look like below:



Deploy The Project:



Final Look:



Thanks & Have Fun!! :)

1 comment:

  1. Gud article !!! You can check this link also

    Thanks
    Bijay
    http://www.enjoysharepoint.com

    ReplyDelete