Thursday, September 30, 2010

How to change Web Part Title Programmatically in SharePoint 2010?

How to change Web Part Title Programmatically in SharePoint 2010?
Generally, Web part title is set in the web part description file. But sometimes we need to set the web part title programmatically. (e.g. changing web part title after changing a value in drop-down control in the web part). We can change web part title by writing following code in the RenderWebPart method of the web part.
This.title = “MyWebPartTitle”;
After this we need to save the title using following code, otherwise changed title won’t appear on the web part title bar.
this.SaveProperties = true;
But there are some cases where this simple trick doesn’t actually work.
· User who is accessing the web part doesn’t have enough permission to save web part properties, setting this.SaveProperies to true throws Permission Exception. This can be handled by writing following line of code

if (SPContext.Current.Web.DoesUserHavePermissions(SPBasePermissions.UpdatePersonalWebParts))
this.SaveProperties = true;

· Even some times you will find that web part title doesn’t change till web part is re-loaded. You will need to set the value after the constructor and before Render/RenderWebPart. Otherwise, you will be setting it too early or too late, respectively.
There are two scenarios
1. If you do not have a TitleBarWebPart on your page, then you can set web part title by overriding OnPreRender method.
2. You have TitleBarWebPart on your page (as is the case with web part page templates , where you can add/remove web parts from a page).
In this case you can set web part title in web part PreRender method. This is due to the fact the TitleBarWebPart generates unique names of each web part in its PreRender method.

void trendDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
string trendType = ((DropDownList)sender).SelectedItem.Value;
if (trendType == "QuestionTrend")
this.Title = Data for Questions;
else if (trendType == "BestPracticeTrend")
this.Title = Data for BestPractice;
if (SPContext.Current.Web.DoesUserHavePermissions(SPBasePermissions.UpdatePersonalWebParts))
this.SaveProperties = true;
}