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

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;
}
}
}

About these ads

9 Comments

  1. Khushi says:

    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. pathikhrawal says:

    Hi Khushi,

    Existing web Parts, Do you mean out of box Web Parts?

  3. Khushi says:

    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

  4. http://fastingforweightloss.net says:

    Yay google is my queen assisted me to find this outstanding website!

  5. Anna says:

    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.

  6. kksan says:

    Thank you so much, worked like a charm!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 81 other followers

%d bloggers like this: