Updating webpart properties from outside the tool pane

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();
     }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>