SharePoint 2010: how define custom properties in visual web-parts

by Curia Damiano 23. May 2011 21:44

SharePoint 2010 introduces the concept of visual web-part, witch, very simply, is an ascx UserControl called from a web-part.

The fact is that you define custom properties in the web-part class, but your ascx control doesn't know the web-part, so... to define custom properties to be used in the ascx control, follow this guide:

  • define the custom property in your web-part class:
            [DefaultValue(3),
             WebBrowsable(true),
             Personalizable(PersonalizationScope.Shared),
             Category("MyCategory"),
             WebDisplayName("Max number of rows"),
             WebDescription("Max number of rows to be shown in the grid")]
            public int MaxNumberOfResults { get; set; }
  • define a web-part derived property in the web-part user-control:
            public MyWebPart WebPart;
  • assign the user-control property in the CreateChildren virtual method of the web-part:
            protected override void CreateChildControls()
            {
                Control control = Page.LoadControl(_ascxPath);
                ((WebParts_MasterLatestNewsUserControl)control).WebPart = this;
                Controls.Add(control);
            }
  • in your user-control, use the web-part properties of your web-part using the previous property:
            myGrid.PageSize = WebPart.MyCustomProperty;

You can find a more complete guide in the posts How do I create custom properties in Visual Web Parts? and SharePoint 2010 Visual Web Parts.

Tags:

SharePoint

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

Contacts and CV

Swiss mobile: +41 76 50 40 60 2
Italian mobile: +39 348/360.25.73
skype: curia.damiano
 

About the author

Damiano Curia is an independent SharePoint and .NET architect. He is specialized on Microsoft technologies and products, in particular .NET/C#, SharePoint, SQL Server and Windows Server. To highlight his technical knowhow, since 2005 he has got 20+ Microsoft certifications. Continue here...

View my profile on LinkedIn

A passion of him is sport. He's training very hard at tennis, (trying to) play in the style of his favorite tennis players, Pete Sampras and Roger Federer.

Finally, his second hobby is photography. You can find his best shots here, he hopes you'll enjoy them!

Month List