Updating webpart properties from outside the tool pane

12 July 2008

Today I created a webpart that contained a form. I wanted the input values from the form to be persisted in the same way as normal webpart properties that are set through the toolpane. To achieve this, I added appropriate attributes to the property I wanted to persist (notably WebBrowsable(false), as I did not want the property to be edited through the UI). I also ensured that the SetPersonalizationDirty() method was called after the property was set - this is crucial to ensure that the value is persisted. The code below illustrates this:

public class SavedSearch : System.Web.UI.WebControls.WebParts.WebPart
{
     private string _savedFreeTextSearch;
     private TextBox _inputBox;
     private Button _inputButton;
     private Label _label;

     [WebBrowsable(false),
     Personalizable(PersonalizationScope.Shared),
     DefaultValue("")]
     public string SavedFreeTextSearch
     {
         get { return _savedFreeTextSearch; }
         set { _savedFreeTextSearch = value; }
     }

     protected override void CreateChildControls()
     {
         _label = new Label();
         _label.Text = this.SavedFreeTextSearch;
         this.Controls.Add(_label);

         _inputBox = new TextBox();
         this.Controls.Add(_inputBox);

         _inputButton = new Button();
         _inputButton.Click += new EventHandler(_inputButton_Click);
         this.Controls.Add(_inputButton);

         base.CreateChildControls();
     }

     private void _inputButton_Click(object sender, EventArgs e)
     {
         this.SavedFreeTextSearch = _inputBox.Text;
         _label.Text = this.SavedFreeTextSearch;
         this.SetPersonalizationDirty();
     }
}



permalink   (currently 1 comments)

Add A Comment

Your Name:
* Please enter the code: Captcha Image
   

* Please enter your message:  

Previous Comments

Mark Stokes
23 September 2008

Hey Rob!

Hope everything s going well with you and your new job.

Great tip this, but I am having a problem making it work with with publishing Pages. It throws a Exception when the page needs to be checked out before updating the web part properties.

I ll try to post a solution when I find one (and if I have time!)

Mark
http://sharepointstudio.com