Change property in webpart by code in sandbox solution

926 Views Asked by At

This is the way I save a property of my webpart in a farm solution:

SPContext.Current.Web.AllowUnsafeUpdates = true;
SPFile file = SPContext.Current.File;
SPLimitedWebPartManager mgr = file.GetLimitedWebPartManager(PersonalizationScope.Shared);

for (int index = 0; index < mgr.WebParts.Count; index++)
{
    if (mgr.WebParts[index].ID == this.ID)
    {
        ((MyWebpartType) mgr.WebParts[index]).MyStringProperty = "Hello World!";
        mgr.SaveChanges(mgr.WebParts[index]);
    }
}
SPContext.Current.Web.AllowUnsafeUpdates = false;

Works fine.

Now I have to achieve the same but in a sandbox solution but there is no SPLimitedWebPartManager available.

So how can I change a webpart property by code inside a sandbox solution webpart?

2

There are 2 best solutions below

1
ChongYong Chin On

You may define your own custom webpart property as below:

 public partial class BannerSlider : System.Web.UI.WebControls.WebParts.WebPart
    { 
        [WebBrowsable(true),
        Personalizable(PersonalizationScope.Shared),
        WebDescription("My WebPart Property"),
        Category("Custom Properties"),
        WebDisplayName("My WebPart Property")]
        public string MyProperty
        {
            get { return __myProperty; }
            set { _myProperty= value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
             this.MyProperty = "Hello World";
2
Marc On

Found the solution, a call to SetPersonalizationDirty() in the webpart saves all properties.