I've been down this route several times before and I've never found a
solution. I need to be able to save a Web Part property
programmatically, like when someone clicks a button/link, chooses a menu
option, leaves the page, etc.
I have set my property's WebPartstorage attribute to Storage.Personal
and I have followed all that the SDK has to say about using SaveChanges
and/or SaveProperties to no avail. I've included my complete test Web
Part class in C# below. Can anyone help me isolate where I'm going
astray?
Since I'm accessing the Web Part property through the SharePoint object
model, I have tried to use the SaveChanges method of the
SPWebPartCollection class to save my changes as follows:
//Begin C# code -------------------------------------------------
private const string defaultText = "";
private string text = defaultText;
[Browsable(true),
Category("Miscellaneous"),
DefaultValue(defaultText),
WebPartStorage(Storage.Personal),
FriendlyName("Text"),
Description("Text Property")]
public string Text
{
get { return text; }
set { text = value; }
}
private Button button = null;
protected override void CreateChildControls()
{
try
{
this.Controls.Add(
new LiteralControl("<h1>Text: " + Text +
"</h1>"));
button = new Button();
button.Text = "Submit";
this.Controls.Add(button);
}
catch{}
}
protected override void RenderWebPart(HtmlTextWriter output)
{
try
{
EnsureChildControls();
RenderChildren(output);
}
catch{}
}
private void button_Click(object sender, EventArgs e)
{
try
{
SPWeb web = SPControl.GetContextWeb(Context);
SPFile file = web.GetFile(Context.Request.Path);
SPWebPartCollection pageWebParts =
file.GetWebPartCollection(Storage.Shared);
Text = "New Value";
pageWebParts.SaveChanges(this.StorageKey);
}
catch{}
}
//End C# code -------------------------------------------------
I thought that maybe I could change the Web Part property while it was
actively being rendered, so I attempted to set the SaveProperties
property of the Web Part class to true. But the changes are still NOT
stored in the database.
I tried using the following RenderWebPart instead:
//Begin C# code -------------------------------------------------
protected override void RenderWebPart(HtmlTextWriter output)
{
try
{
Text = "New Value";
this.SaveProperties = true;
EnsureChildControls();
RenderChildren(output);
}
catch{}
}
//End C# code -------------------------------------------------
I also tried using the following button_Click instead:
//Begin C# code -------------------------------------------------
private void button_Click(object sender, EventArgs e)
{
try
{
Text = "New Value";
this.SaveProperties = true;
}
catch{}
}
//End C# code -------------------------------------------------
None of this code persist my changes into the database. I even tried
doing both SaveChanges and SaveProperties but, as they say in the UK,
"no joy".
Can anyone help?
Do you know someone who can help? Share a link to this thread on twitter, or facebook.