SharePoint 2010

SharePoint 2010: Setting Value for Web Part’s Custom Properties while Adding Web Part to Page Programmatically


To set the Custom Properties of web part through code while adding Web Part to Page programmatically, we can use Reflection to do this, Below is code on how to achieve this.

if (string.Equals(webPart.GetType().ToString(), “MyCustomWebpart”))
{
PropertyInfo[] pinProperties = webPart.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

foreach (PropertyInfo pinProperty in pinProperties)
{
if (pinProperty.Name == “Some Property”)
{
pinProperty.SetValue(webPart, “/Some Value”, null);
break;
}
}
}

10 thoughts on “SharePoint 2010: Setting Value for Web Part’s Custom Properties while Adding Web Part to Page Programmatically

  1. Informative article Pathik. Didn;t try your code. right now just a quick question. Can we change the custom web part properties of the exisiting web part? Can we persist those properties changes for each user as a personalize webpart property? I mean if i have a property “Name” on the web part. If “A” User set this property as “A” and “B” User set its property as “B”. is it possible that when user “A” browse the page he/she will be able to see the name property “A” or whatever he/she set it before.

    PS: SP2010.

    Thanks,
    Khushi

  2. Hi Pathik, I mean by Existing webparts, the custom web part added to the web part page by the user. Also, I have one more question. Is this(personalization) restricted to mySite only? I have TeamSite as HomePage and have few webparts on it that has few properties and user can set those propertiers according to their preference? Is personalization is not allowed to a teamSite or Publishing Site?

    Thanks
    Khushi

  3. Thank you for this information! It solved my problems!

    I had struggled with it for some time. The only thing I needed to add to your code was saveChanges() to the SPLimitedWebPartManager.

  4. I have a Question. I need to set a dropdown value inside a webpart. Can anyone provide a solution for this. Is there any way to edit an existing webpart and set the default value. Kindly help me

Leave a comment