Programmatically Adding Controls to a Sitefinity Page
The PageManager in Sitefinity has a method called CreateControl that is overloaded to allow both Compiled (dll) controls as well as simple User Controls (.ascx files) to be initialized and added to a Sitefinity page. Both overloads require a string containing the name of the ContentPlaceholder that will hold the control, which is defined in the .master file backing a Sitefinity template.
CreateControl Method and Sample Code
For compiled web controls, the signature of the CreateControl method looks like this:
CreateControl<T>(System.Web.UI.Control control, string placeHolder)
Here is an example code snippet that creates a NewsView control and adds it to a page.
The method for UserControls, on the other hand, accepts a string with the relative path to the user control (such as “~/widgets/control.ascx”):
CreateControl<T>(string controlPath, string placeHolder)
Here is an example code snippet that creates an instance of a user control and adds it to the page.
In both methods, the generic type <T> should be PageControl.
Adding Controls in Order
Controls added to Sitefinity Pages load at runtime in no particular order, and even if you add them in a specific sequence, they may load on the page in a different order.
Fortunately, you can specify the order the widgets should load by using the SiblingId property of the control, which refers to the ID of the control that should precede it in the placeholder.
The first control should have this value be empty, since it is at the top and has no previous sibling control. After adding the control, save the ID, and assign it to the SiblingID property of the next control you wish to load.
Here is a simple example that demonstrates this, adding the three controls so they load in order on the page. This example demonstrates using a User Control, but the property works for compiled controls as well.
Latest posts by selaromdotnet (see all)
- Restarting a Specific Azure Web App Instance - January 13, 2021
- Adding Ratings and Reviews to Sitecore Commerce with YotPo - November 13, 2018
- Sourcetree Suddenly Prompting for Github Credentials - February 22, 2018