7.11 Add Controls to a Web Form Dynamically


Problem

You need to add a Web control to a Web page at run time and handle its events.

Solution

Create a control object, add it to the Controls collection of a container control, and use the AddHandler statement to connect any event handlers. You must create the control after every postback.

Discussion

You can use a technique to add Web controls to a Web page that's similar to the way you would add Windows controls to a form, but there are some differences, including the following:

  • Dynamically added controls will exist only until the next postback. If you need them, you must re-create them when the page is returned. This requirement doesn't prevent you from writing code that handles their events, however.

  • Dynamically added controls aren't as easy to position. Typically, you'll use literal controls containing HTML code (such as the line break < br >) to separate more than one dynamically created control.

  • Dynamically created controls should be placed in a container control (such as a Panel or a LiteralControl ) rather than directly on the page itself, which makes it easier to position them.

  • If you want to interact with the control later, you should give it a unique ID. You can use this ID to retrieve the control from the Controls collection of its container.

The best place to generate new controls is in the Page.Load event handler, which ensures that the control will be created each time the page is served . In addition, if you're adding an input control that uses view state, the view state information will be restored to the control after the Page.Load event fires. That means a dynamically generated text box will retain its text over multiple postbacks, just like a text box that's defined in the .aspx file. Similarly, because the Page.Load event always fires before any other events take place, you can re- create a control that raises server-side events and its event-handling code will be triggered immediately after the Page.Load event. For example, this technique allows you to dynamically generate a button that can respond to user clicks.

The following example demonstrates all these concepts. It generates three dynamic server controls (two buttons and a text box) and positions them using literal controls that act as separators. The buttons are connected to distinct event handlers. The text box is given a unique identifier so that its text can be retrieved later, in response to the button clicks. Figure 7.7 shows the page in action.

click to expand
Figure 7.7: Dynamically generated controls.

The full code is shown here:

 using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Security; public class DynamicControls : System.Web.UI.Page {     protected System.Web.UI.WebControls.Label lblMessage;     protected System.Web.UI.WebControls.Panel pnl;     // (Designer code omitted.)     private void Page_Load(object sender, System.EventArgs e) {              // Create a dynamic button.         Button dynamicButton = new Button();         dynamicButton.Text = "Dynamic Button A";         // Connect an event handler.         dynamicButton.Click += new EventHandler(cmdDynamicA_Click);         // Add the button to a Panel.         pnl.Controls.Add(dynamicButton);                      // Add a line break separator.         pnl.Controls.Add(new LiteralControl("<br>"));         // Create a second dynamic button.         dynamicButton = new Button();         dynamicButton.Text = "Dynamic Button B";         dynamicButton.Click += new EventHandler(cmdDynamicB_Click);         pnl.Controls.Add(dynamicButton);         // Add a line break separator.         pnl.Controls.Add(new LiteralControl("<br><br>"));         // Create a dynamic textbox.         TextBox dynamicText = new TextBox();         pnl.Controls.Add(dynamicText);         // Assign a unique ID so the textbox can be retrieved         // from the control collection later.         dynamicText.ID = "DynamicText";     }     private void cmdDynamicA_Click(object sender, System.EventArgs e) {              lblMessage.Text = "Clicked A";         GetText();     }          private void cmdDynamicB_Click(object sender, System.EventArgs e) {              lblMessage.Text = "Clicked B";         GetText();     }     private void GetText(){         lblMessage.Text += "<br><br>";         foreach (Control ctrl in pnl.Controls){             if (ctrl.ID == "DynamicText"){                 lblMessage.Text += "TextBox contains: " +                   ((TextBox)ctrl).Text;             }         }     } } 

If you need to dynamically create complex layouts that include some prebuilt control "groups," you might prefer to use user controls and load them dynamically into a page. This technique is demonstrated in recipe 7.13.




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net