Tuesday, July 24, 2012

dynamically make ASP.NET web forms controls

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master"
      AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApp._Default"
      %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
   <asp:Panel runat="server" ID="OuterContainer">
      <asp:CheckBox ID="FooBox" runat="server" Text="Foo" />
   </asp:Panel>
</asp:Content>

 
 

The preceeding web form has the following code behind.

using System;
using System.Web.UI.WebControls;
namespace WebApp
{
   public partial class _Default : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {
         CheckBox barCheckBox = new CheckBox();
         barCheckBox.Text = "Bar";
         barCheckBox.ID = "BarBox";
         OuterContainer.Controls.Add(barCheckBox);
      }
   }
}

 
 

As you can see the FooBox is made in the web form itself while the BarBox is made in the code behind. The result looks like so:

Share photos on twitter with Twitpic

I have heard that Page_Init is the really the place to make dynamic controls. I was able to refactor my code behind to be as such:

using System;
using System.Web.UI.WebControls;
namespace WebApp
{
   public partial class _Default : System.Web.UI.Page
   {
      private CheckBox barCheckBox;
      
      protected void Page_Init(object sender, EventArgs e)
      {
         barCheckBox = new CheckBox();
         barCheckBox.Text = "Bar";
         barCheckBox.ID = "BarBox";
      }
      
      protected void Page_Load(object sender, EventArgs e)
      {
         OuterContainer.Controls.Add(barCheckBox);
      }
   }
}

 
 

Whatever.

No comments:

Post a Comment