Programmatically adding User Controls
Hi all,
I am having some problems adding user controls to pages in Sitefinity 4.0. Below is a list of things im trying to achieve.
1) To create a page with the Sitefinity API.
2) To add custom user controls to this page.
3) To set custom properties of each control on this page.
I'm working from the following documentation.
http://www.sitefinity.com/40/help/developers-guide/sitefinity-essentials-pages-adding-and-removing-controls.html
Running as a Web Application
I started with a basic web application, I have been able to add user controls using the following code.
PageDraftControl draftControl = manager.CreateControl<PageDraftControl>(
"~/controls/mycontrol.ascx"
,
"holder"
);
draftPage.Controls.Add(draftControl);
dynamic mycontrol = LoadControl(
"~/controls/mycontrol.ascx"
);
mycontrol.Message =
"Hello World"
;
PageDraftControl draftControl = manager.CreateControl<PageDraftControl>(mycontrol,
"holder"
);
draftPage.Controls.Add(draftControl);
MyControl mycontrol =
new
MyControl();
mycontrol.Message =
"Hello World"
;
PageDraftControl draftControl = manager.CreateControl<PageDraftControl>(mycontrol,
"holder"
);
draftPage.Controls.Add(draftControl);
In terms of being able to programmatically set properties on User Controls when adding user controls to pages, I have been able to find a work around to this problem using the following code. I hope others find this useful.
this is in reference to the following documentation.
http://www.sitefinity.com/40/help/developers-guide/sitefinity-essentials-pages-adding-and-removing-controls.html
dynamic usercontrol = BuildManager.CreateInstanceFromVirtualPath(
"~/mycontrol.ascx"
,
typeof
(UserControl));
usercontrol.Message =
"Hello World"
; // Some public property on this user control.
PageDraftControl pageDraftControl = pageManager.CreateControl<PageDraftControl>();
pageDraftControl.ObjectType =
"~/mycontrol.ascx"
;
pageDraftControl.PlaceHolder =
"ContentPlaceHolder1"
;
pageManager.ReadProperties(usercontrol, pageDraftControl); // Voodoo here
draftPage.Controls.Add(pageDraftControl);
...