简体   繁体   中英

SharePoint: add properties to a webpart from code behind

In the codebehind of a page.

How do i get hold of a webpart that exist on the page, then add properties to that webpart using c#.

The webpart exists withing a webpartzone.

Do i need to do anything with SPWebPartManager?

Use SPWeb.GetLimitedWebPartManager . The following example demonstrates updating a property in a list view web part:

using (SPLimitedWebPartManager webPartManager =
    SPContext.Current.Web.GetLimitedWebPartManager("default.aspx",
        PersonalizationScope.Shared))
{
    try
    {
        foreach (WebPart webPart in webPartManager.WebParts)
        {
            if (webPart.Title == "Web Part To Update")
            {
                ListViewWebPart listViewWebPart = (ListViewWebPart)webPart;
                // TODO: Set property on web part
                webPartManager.SaveChanges(listViewWebPart);
                break;
            }
        }
    }
    finally
    {
        webPartManager.Web.Dispose();
    }
}

Instead of default.aspx you need to use the name of the current page relative to the SPWeb.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM