Create Visual Webpart with Custom Properties in SharePoint 2010

Let's see how to create custom properties to a Visual Web Part in SharePoint 2010.

Now let us see the basic architecture of Web Part in SharePoint 2010. In SharePoint 2010, there is a Web Part class and a User Control class in a Visual Web Part. The Associated User Control Class is loaded during execution of Web Part class through "CreateChildControl" method. So, we have to add Custom Properties to Web Part class.

following is the SharePoint 2010 Visual Web Part architecture

SharePoint 2010 Visual WebPart Architecture

Now, follow below steps to create a Visual Web Part with Custom Properties. I will show how to create a drop down menu in this article. similarly, you can also create textbox, Boolean value,check box etc.
Refer MSDN for Different Custom Properties

Add Custom Properties to a Visual Web Part:
  • Add a Visual Web Part to your project.
  • Replace the code in the Web Part class with below code.

Visual WebPart - WebPart Class View

 protected override void CreateChildControls()
   Control control = Page.LoadControl(_ascxPath);
   if (control != null)
    ((LandingPageSites2UserControl)control).UserProperties = this;

  public enum WebPartCustomProp

  Category("Custom Configurations"),
  WebDisplayName("WebPart Properties"),
  WebDescription("Select a properties to change the WebPart display")]

  public WebPartCustomProp WebPartProperty { get; set; }

Using Custom Properties in Visual Web Part:
  • Now add the below code in the User Control Class. 

  public LandingPageSites2 UserProperties { get; set; }

  protected void Page_Load(object sender, EventArgs e)
    if (!Page.IsPostBack)
       lblProject.Text = this.UserProperties.WebPartProperty.ToString();
  • Build and deploy the solution.
  • Add the Web Part to a Page and Edit the Web Part to see properties.

visual webpart custom properties - SP 2010
  • Click OK, You can see your Custom Properties displayed on your page.
Hope this is helpful for you.

Sudheer Gangumolu

I'm a Software Analyst / Developer / Blogger, having good experience in working with different flavors & Customization of SharePoint (i.e.,SP O365 / 2013 / 2010 / 2007) and .Net Apps. Currently, working on SharePoint 2013 / SharePoint O365. Guiding people on my technologies.

    Blogger Comment
    Facebook Comment


Post a Comment