Question about webpart properties
-
10-12-2019 - |
Question
How can I access a custom property in my webpart?
I have a page that contains webparts, which contains multiple instances of the same custom webpart. I wanted to use the .webpart
file to add my own custom property like :
<property name="CustomProperty" type="string">value</property>
so I can treat each webpart according to this value.
I can't seems to get hold of this property. I can access title , description etc. but not my property.
I managed to create a custom property which I can handle while editing the webpart at runtime, but I would like to set it once in the .webpart
file.
Solution
as alex stated,
Also you need to make sure your actualy putting in the values first ;), You need a constant with a value or "" , then the getter setter with that const varible to get and set, you finaly need to add a constructor that contains the private varibles that pass the const to the private:
create your base class:
add const:
//this is your default string
const string c_MyStringDefault = "Sample String";
add private string:
//this will be used internaly through the constructor
private string _myString;
add constructor:
// Constructor
public CustomPropertyWebPart()
{
// Initialize private variables.
_myString = c_MyStringDefault;
}
add the get/set method
// Creates a custom property that is a string.
// This property will be displayed as a text box in the
// property pane.
// Create a custom category in the property sheet.
[Category("Custom Properties")]
// Assign the default value.
[DefaultValue(c_MyStringDefault)]
// Property is available in both Personalization
// and Customization mode.
[WebPartStorage(Storage.Personal)]
// The caption that appears in the property sheet.
[FriendlyNameAttribute("Custom String")]
// The tool tip that appears when pausing the mouse pointer over
// the friendly name in the property pane.
[Description("Type a string value.")]
// Display the property in the property pane.
[Browsable(true)]
[XmlElement(ElementName="MyString")]
// The accessor for this property.
public string MyString
{
get
{
return _myString;
}
set
{
_myString = value;
}
}
http://msdn.microsoft.com/en-gb/library/dd584174(v=office.11).aspx
OTHER TIPS
In your custom web part create a public property:
[Browsable(false)]
public string Value { get; set; }
Then you can access the public property and set it in your CustomWebpart.webpart file.
<?xml version="1.0" encoding="utf-8"?>
<webParts>
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
<metaData>
<type name="CustomWebpart, $SharePoint.Project.AssemblyFullName$" />
<importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
</metaData>
<data>
<properties>
<property name="Title" type="string">myWebpart</property>
<property name="Description" type="string">My Visual WebPart</property>
<property name="Value" type="string">your value</property>
</properties>
</data>
</webPart>
</webParts>