Create Visual Web part 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
Code:

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

  public enum WebPartCustomProp
  {
   AllProjectPortals,
   MyProjectPortals
  }

  [WebBrowsable(true),
  Category("Custom Configurations"),
  Personalizable(),
  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. 
Code:

  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.
Create Visual Web part with Custom Properties in SharePoint 2010 Create Visual Web part with Custom Properties in SharePoint 2010 Reviewed by Sudheer Gangumolu on December 31, 2014 Rating: 5

No comments: