For adding custom properties to our web part we need to do the following
1) Create property.
2) Decorate the property with the following attributes
WebBrowsable – To allow your property to be visible within SharePoint.
WebDisplayName– To provide display name to the property.
WebDescription– To provide description for that property.
Personalizable – To define the scope of it i.e either User or Shared through PersonalizationScope enumeration.
Let’s take a simple example wherein we have 2 properties defined, user will enter value for them and finally when the web part is rendered, we would be displaying their sum within the web part.
namespace AdditionWebPart
{
public class SumWebPart : WebPart{
private int firstVariable;
[WebBrowsable(true),
WebDisplayName(“First Value”),
WebDescription(“Enter value for first variable”),
Personalizable(PersonalizationScope.User)]
public int FirstVariable
{
get { return firstVariable; }
set { firstVariable = value; }
}
private int secondVariable;
[WebBrowsable(true),
WebDisplayName(“Second Value”),
WebDescription(“Enter value for second variable”),
Personalizable(PersonalizationScope.User)]
public int SecondVariable
{
get { return secondVariable; }
set { secondVariable = value; }
}
protected override void Render(System.Web.UI.HtmlTextWriter writer){
writer.Write(“The total is “ +this.calcTotal(this.firstVariable,this.secondVariable));
}
private int calcTotal(int a, int b){
return a + b;
}}}
Put the following attribute in your assemblyinfo.cs file
[assembly: AllowPartiallyTrustedCallers]
Strong sign the assembly and install it in GAC.
Open the web.config of your site where you want this webpart
Make a safecontrol entry within the web.config for your webpart.
<SafeControl Assembly=“AdditionWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5f7492d3f59e0c4b“ Namespace=“AdditionWebPart“ TypeName=“*“ Safe=“True“ />
The name of the assembly,it’s version, culture and public key token information can be found by right clicking the assembly within gac and selecting properties.
Bye….
Nice, you just solve me half of the problem, thanks
Now I would like this new custom property to be a dropdown menu (choice)
How can this be achieved?
Regards,
LikeLike
Hi Mario,
For showing the drop down you can define your property as enum.
public enum myChoiceEnum
{
choice1,
choice2,
choice3,
choice4
};
private myChoiceEnum _myEnum;
[WebBrowsable(true),
WebDisplayName(“My Choice”),
WebDescription(“Select a value”),
Personalizable(PersonalizationScope.User)]
public myChoiceEnum MyEnum
{
get { return _myEnum; }
set { _myEnum = value; }
}
Try it!!
LikeLike
Thank you Nishant,
Works like a charm 😉
LikeLike
How would you add a textarea?
LikeLike
Hi Nishant
if i want one of the custom property to be password field how can i achieve it
LikeLike