Home > Uncategorized > ASP.NET Adding Dynamic Controls in EventHandlers

ASP.NET Adding Dynamic Controls in EventHandlers

As most of you guys know, adding controls dynamically to aspx pages is a pain. There is always a tricky situation that messes up the eventhandling or viewstate or diffuculties in walking through the child controls through the container controls like placeholder. I faced one such with dynamic controls being added in a button.click handler. Just so that you or I can save some time here are some reads to look for before you use dynamic controls in your application:

Page Lifecycle

  1. http://msdn2.microsoft.com/en-us/library/ms178472 (read everything)
  2. http://www.eggheadcafe.com/articles/20051227.asp 

(Peter’s table is great in 2. Pay attention in particular to events LoadViewState, ProcessPostData1, ProcessPostData2 and their order in Page’s timeline. And then read about it from Dino’s excellent article abt ProcessPostData1 and ProcessPostData2 sweeps here. Then read everything Scott has to say:

Scott‘s Articles

  1. Dynamic Controls in ASP.NET
  2. Working With Dynamically Created Controls
  3. Dynamic Web Controls, Postbacks, and View State
  4. Control building and ViewState Redux
  5. Tip: When Adding Dynamic Controls, Specify an ID

In short these are the general things that you would want to do to ensure all work smoothly.

1. Add new control to a placeholder’s control collection.

eg:

TextBox myTxtBox = new TextBox();
myPlaceHolder.Controls.Add(myTxtBox);

2. Only after step 1, set the attributes for the dynamically created control.

myTxtBox.ID ="myDyna"
myTxtBox.Text = "Hello! I am Dyna"

3. Ensure you specify the ID’s for the controls you add.

4. If controls are dynamically created in an EventHandler like Button.Click or DropDownList.SelectedIndexChanged then follow the pattern in Dino’s article. Which if I may summarize is to:

  • Isolate Control Factory methods from EventHandlers
  • Use ViewState or some other persistent flag (dropdownlist.SelectedIndex != -1, etc) to check if the controls have been added dynamically.
  • If the flag is true then re-create them again in page load so that during ProcessPostData events the controls are found and viewstate restored for them from the temporary collection as described in Dino’s article.
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment