How To Add Custom Properties In Visual Webpart

Create a Visual webpart and add the code, as shown below.

  1. public partial class VisualWebPart1: WebPart   
  2. {  
  3.         [Personalizable(PersonalizationScope.Shared), WebBrowsable(true),  
  4.             WebDisplayNameAttribute("Street name"), WebDescription("Can store street value as string"), CategoryAttribute("Address")  
  5.         ]  
  6.         public String Street {  
  7.             get;  
  8.             set;  
  9.         }  

Now, deploy the Visual webpart. The property will be as shown below:

Now, how to get that property in Visual WebPart? Here is the code:

Code

  1. protected void Page_Load(object sender, EventArgs e) {  
  2.     if (!Page.IsPostBack) {  
  3.         lblStreet.Text = this.Street;  
  4.     }  
  5. }  

Key points to create a property:

Personalizable()- This attribute is used to specify that the property is saved in content database. It accepts two arguments,
  • PersonalizationScope.Shared – It specifies that all users share common property.
  • PersonalizationScope.User – It specifies that different users can have different properties.
Default value is PersonalizationScope.Shared

WebBrowsable() – It specifies that property is editable via editor pane if Browser Default value is true.
WebDisplayNameAttribute("Street name") – It specifies the display name Default value is property name if WebDisplayNameAttribute is not mentioned.
WebDescription("Can store street value as string") – describes about property, below, we can see WebDisplayNameAttribute which is street and WebDescription.

CategoryAttribute("Address") – Street comes under address category.

If no category is given for a property, then property will appear under miscellaneous section.

Types of properties
  • Boolean – CheckBox
  • DateTime – TextBox
  • Text – TextBox
  • Integer – TextBox
  • Enum - DropDown
How can dropdown be used as a property?

Code

  1. public enum MyCityName {  
  2.     Gurgaon,  
  3.     GuruGram  
  4. };  
  5. [Personalizable(), WebBrowsable(), Category("Address")]  
  6. public MyCityName CityOption {  
  7.     get;  
  8.     set;  
  9. }  

As shown below, we can get selected dropdown value.

  1. protected void Page_Load(object sender, EventArgs e) {  
  2.     if (!Page.IsPostBack) {  
  3.         lblCity.Text = this.CityOption.ToString();  
  4.     }  
  5. }