Programmatically Adding Controls to a Sitefinity Page

By in
No comments

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.

View code sample on Gist

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.

View code sample on Gist

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.

View code sample on Gist

The following two tabs change content below.

selaromdotnet

Senior Developer at iD Tech
Josh loves all things Microsoft and Windows, and develops solutions for Web, Desktop and Mobile using the .NET Framework, Azure, UWP and everything else in the Microsoft Stack. His other passion is music, and in his spare time Josh spins and produces electronic music under the name DJ SelArom. His other passion is music, and in his spare time Josh spins and produces electronic music under the name DJ SelArom.