Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add ScriptManager to Page Programmatically?

I am developing a WebPart (it will be used in a SharePoint environment, although it does not use the Object Model) that I want to expose AJAX functionality in. Because of the nature of the environment, Adding the Script Manager directly to the page is not an option, and so must be added programmatically. I have attempted to add the ScriptManager control to the page in my webpart code.

protected override void CreateChildControls() {     if (ScriptManager.GetCurrent(Page) == null)     {         ScriptManager sMgr = new ScriptManager();         // Ensure the ScriptManager is the first control.         Page.Form.Controls.AddAt(0, sMgr);      } } 

However, when this code is executed, I get the following error message:

"The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases."

Is there another way to add the ScriptManager to the page from a WebPart, or am I going to have to just add the ScriptManager to each page (or master page) that will use the WebPart?

like image 592
Kyle Trauberman Avatar asked Oct 08 '08 17:10

Kyle Trauberman


1 Answers

I was able to get this to work by using the Page's Init event:

protected override void OnInit(EventArgs e) {     Page.Init += delegate(object sender, EventArgs e_Init)                  {                      if (ScriptManager.GetCurrent(Page) == null)                      {                          ScriptManager sMgr = new ScriptManager();                          Page.Form.Controls.AddAt(0, sMgr);                      }                  };     base.OnInit(e); } 
like image 61
Kyle Trauberman Avatar answered Sep 24 '22 14:09

Kyle Trauberman