How can I dynamically instantiate a web part layout for a specific web part in C#

Dominic Carvalho asked on September 25, 2018 11:54

Hey, I am dynamically instantiating web parts on my Kentico page by first getting the web part and then setting the properties in the code and then adding it to the page.

This is working well, When I go to my page in the Design tab I can see my web part has been added to the page with all the properties I set in the code.

The only problem is that I have to manually select the layout for that web part I created. Is there a way to also set the layout using the layout code name for a specific web part ?

For e.g:

WebPart.SetValue ("Layout", "LayoutCodeName"); The same way I set other props on the web part. Or WebPart.SetLayout();

Any help will be greatly appreciated.

Kind Regards

Dominic

Recent Answers


Arun Kumar answered on September 25, 2018 14:38

Have you checked this documentation?

You can do this by something like this

// Gets the web part layout
WebPartLayoutInfo updateLayout = WebPartLayoutInfoProvider.GetWebPartLayoutInfo("NewWebpart", "NewLayout");
if (updateLayout != null)
{
    // Updates the web part layout properties
    updateLayout.WebPartLayoutDisplayName = updateLayout.WebPartLayoutDisplayName.ToLower();

    // Saves the changes to the database
    WebPartLayoutInfoProvider.SetWebPartLayoutInfo(updateLayout);
}
1 votesVote for this answer Mark as a Correct answer

Dominic Carvalho answered on September 26, 2018 12:41

Hey Arun Kumar Thanks for the reply, I managed to get the layout instantiated on the web part. Turns out that their is a property on the webpart to set the webpart Layout with the key value pair.

newWebPart.SetValue("webpartlayout", "Text_FullWidth_100");

I just specify the webpartlayout key and the set that layout to my webpart layout name and it worked perfectly.

Kind Regards

Dominic

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.