?
Solved

How do you Programmatically change custom WebPart attributes in SharePoint 2010?

Posted on 2011-10-27
7
Medium Priority
?
1,548 Views
Last Modified: 2012-05-12
I have a web part with custom attributes. I need to be able to change these attributes from within the WebPart, and not just on the [Edit Web Part] Tool bar.
0
Comment
Question by:Rahsaan-Pringle
  • 4
  • 3
7 Comments
 
LVL 32

Expert Comment

by:Jamie McAllister MVP
ID: 37043623
this.MyProperty = "MyValue"  ??
0
 
LVL 32

Expert Comment

by:Jamie McAllister MVP
ID: 37043651
0
 

Author Comment

by:Rahsaan-Pringle
ID: 37059951
This is my first swipe at a working answer. I'll add more complete code as I develop it.
?SPWeb
Microsoft.SharePoint.SPWeb
    base {Microsoft.SharePoint.SPSecurableObject}: Microsoft.SharePoint.SPSecurableObject
?SPSite
Microsoft.SharePoint.SPSite
    base {object}: object
    MaxFullUrlLength: 260
    MaxWebNameLength: 256
?SPContext.Current.Site.Url
"http://c4isuite-v4/nrma"
?SPContext.Current.Site.
Identifier expected
?SPContext.Current.Site
{SPSite Url=http://c4isuite-v4/nrma}
    AdministrationSiteType: None
    AllowDesigner: true
    AllowMasterPageEditing: false
    AllowRevertFromTemplate: false
    AllowRssFeeds: true
    AllowUnsafeUpdates: false
    AllWebs: {Microsoft.SharePoint.SPWebCollection}
    ApplicationRightsMask: 9223372036854775807
    Audit: {Microsoft.SharePoint.SPAudit}
    AuditLogTrimmingCallout: ""
    AuditLogTrimmingRetention: 0
    AverageResourceUsage: 0.14024751190444598
    BrowserDocumentsEnabled: true
    Cache: {Microsoft.SharePoint.Administration.SPSiteCollectionPropertyCache}
    CatchAccessDeniedException: true
    CertificationDate: {5/16/2009 3:42:30 PM}
    ContentDatabase: {SPContentDatabase Name=ContentDB_nrma}
    CurrentChangeToken: {1;1;7ee3fbf1-cf8f-4ad6-b335-d359c28746e7;634556965531770000;87540}
    CurrentResourceUsage: 0.0
    DeadWebNotificationCount: 0
    EventReceivers: {Microsoft.SharePoint.SPEventReceiverDefinitionCollection}
    ExternalBinaryIds: {Microsoft.SharePoint.SPExternalBinaryIdCollection}
    FeatureDefinitions: {Microsoft.SharePoint.Administration.SPFeatureDefinitionCollection}
    Features: {Microsoft.SharePoint.SPFeatureCollection}
    GlobalPermMask: -1
    HostHeaderIsSiteName: false
    HostName: "c4isuite-v4"
    ID: {7ee3fbf1-cf8f-4ad6-b335-d359c28746e7}
    IISAllowsAnonymous: false
    Impersonating: false
    IsPaired: false
    LastContentModifiedDate: {10/31/2011 10:22:33 PM}
    LastSecurityModifiedDate: {10/13/2011 8:10:49 PM}
    LockIssue: null
    Owner: {ATFP\Administrator}
    Port: 80
    PortalName: null
    PortalUrl: null
    Protocol: "http:"
    Quota: {Microsoft.SharePoint.Administration.SPQuota}
    ReadLocked: false
    ReadOnly: false
    RecycleBin: {Microsoft.SharePoint.SPRecycleBinItemCollection}
    ResourceQuotaExceeded: false
    ResourceQuotaExceededNotificationSent: false
    ResourceQuotaWarningNotificationSent: false
    RootWeb: {Navy Region Mid-Atlantic}
    SearchServiceInstance: null
    SecondaryContact: {ATFP\daniel.hadden.ctr}
    ServerRelativeUrl: "/nrma"
    ShowURLStructure: false
    SiteSubscription: null
    Solutions: {Microsoft.SharePoint.SPUserSolutionCollection}
    SyndicationEnabled: true
    SystemAccount: {SHAREPOINT\system}
    TrimAuditLog: false
    UIVersionConfigurationEnabled: true
    UpgradeRedirectUri: {http://c4isuite-v4/nrma/default.aspx}
    Url: "http://c4isuite-v4/nrma"
    Usage: {Microsoft.SharePoint.SPSite.UsageInfo}
    UserAccountDirectoryPath: ""
    UserCodeEnabled: true
    UserCustomActions: {Microsoft.SharePoint.SPUserCustomActionCollection}
    UserDefinedWorkflowsEnabled: true
    UserToken: {Microsoft.SharePoint.SPUserToken}
    WarningNotificationSent: false
    WebApplication: {SPWebApplication Name=SharePoint - 80}
    WorkflowManager: {Microsoft.SharePoint.Workflow.SPWorkflowManager}
    WriteLocked: false
    Zone: Default

Open in new window

0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:Rahsaan-Pringle
ID: 37059958
This is my first swipe at a working answer. I'll add more complete code as I develop it.
/// <summary>
        /// http://nikspatel.wordpress.com/2011/02/23/programmatically-modify-the-properties-of-the-sharepoint-web-parts/
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void SvButton_Click(object sender, EventArgs e)
        {
            string wpTitles;
            SPWeb spWeb;
            SPSite SPSite;
            WeatherMap WeatherMap;

            wpTitles = "";
            SPSite = SPContext.Current.Site; 
            spWeb = SPContext.Current.Web;
            spWeb.AllowUnsafeUpdates = true;
            
            SPFile SPFile = spWeb.GetFile("Default.aspx");
            using (SPLimitedWebPartManager SPLimitedWebPartManager = SPFile.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
            {

                foreach (System.Web.UI.WebControls.WebParts.WebPart wp in SPLimitedWebPartManager.WebParts)
                {
                    if (wp.Title == "Weather Map")
                    {
                        try
                        {
                            if (wp is C4ISuite.WeatherMap.WeatherMap)
                            {
                                WeatherMap = (C4ISuite.WeatherMap.WeatherMap)wp.WebBrowsableObject;
                                WeatherMap.Index = 5;
                                SPLimitedWebPartManager.SaveChanges(WeatherMap);
                            }
                        }
                        catch (Exception)
                        {
                            
                            throw;
                        }
                    }
                    else
                    {
                        wpTitles = wpTitles + "| " + wp.Title;
                    }
                }
            }
            spWeb.AllowUnsafeUpdates = false;
        }

Open in new window

0
 

Accepted Solution

by:
Rahsaan-Pringle earned 0 total points
ID: 37060111
This is a more cleaned up version of the working code.
/// <summary>
        /// http://nikspatel.wordpress.com/2011/02/23/programmatically-modify-the-properties-of-the-sharepoint-web-parts/
        /// </summary>
        /// <param name="WebPartTitle">The name of the Web Part to have changes made.</param>
        /// <param name="PageName">The name of the page where the WebPart is being accessed from.</param>
        /// <param name="IndexNumber">The number that the Index is to be set to</param>
        protected void setIndex(string WebPartTitle, string PageName, int IndexNumber)
        {
            SPWeb SPWeb;
            WeatherMap WeatherMap;  /// The Object of the Web Part

            SPWeb = SPContext.Current.Web;
            SPWeb.AllowUnsafeUpdates = true;

            SPFile SPFile = SPWeb.GetFile(PageName);
            using (SPLimitedWebPartManager SPLimitedWebPartManager = SPFile.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
            {
                foreach (System.Web.UI.WebControls.WebParts.WebPart WebPart in SPLimitedWebPartManager.WebParts)
                {
                    if (WebPart.Title == WebPartTitle)
                    {
                        try
                        {
                            if (WebPart is C4ISuite.WeatherMap.WeatherMap)
                            {
                                WeatherMap = (C4ISuite.WeatherMap.WeatherMap)WebPart.WebBrowsableObject;
                                WeatherMap.Index = IndexNumber; /// Index is the Web Part Property that needs to be changed
                                SPLimitedWebPartManager.SaveChanges(WeatherMap);
                            }
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                    }
                }
            }
            SPWeb.AllowUnsafeUpdates = false;
        }

Open in new window

0
 
LVL 32

Assisted Solution

by:Jamie McAllister MVP
Jamie McAllister MVP earned 2000 total points
ID: 37061034
That looks OK to me. Everything disposed appropriately, does the job.
0
 

Author Closing Comment

by:Rahsaan-Pringle
ID: 37089710
This worked
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Planning to migrate your EDB file(s) to a new or an existing Outlook PST file? This video will guide you how to convert EDB file(s) to PST. Besides this, it also describes, how one can easily search any item(s) from multiple folders or mailboxes…
Suggested Courses

612 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question