Wednesday, January 16, 2013

Making controls dynamically in the Page_Init event in ASP.NET web forms isn't too tough.

I just did it for the first time. You are going to have to have some controls (think Panel) to put the code-created controls in. Here is a web form that will work:

<%@ Page Language="C#" AutoEventWireup="true"
      CodeBehind="WhitelistForReroutingAdministration.aspx.cs"
      Inherits="ResponseRedirectWhitelisting.WhitelistForReroutingAdministration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
      Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Whitelist For Rerouting Administration</title>
</head>
<body>
   <form id="form1" runat="server">
      <div style="margin:0 auto; width: 800px;">
         <div style="float:left; width: 400px;">
            <asp:Panel runat="server" ID="LeftPanel"></asp:Panel>
         </div>
         <div style="float:right; width: 400px;">
            <asp:Panel runat="server" ID="RightPanel"></asp:Panel>
         </div>
         <div style="clear:both; height:20px;"></div>
      </div>
   </form>
</body>
</html>

 
 

Here is the magic in the code behind. (not too tough really)

using System;
using System.Web.UI.WebControls;
namespace ResponseRedirectWhitelisting
{
   public partial class WhitelistForReroutingAdministration : System.Web.UI.Page
   {
      protected void Page_Init(object sender, EventArgs e)
      {
         int counter = 0;
         while (counter < 10)
         {
            counter++;
            TextBox textBox = new TextBox();
            textBox.Attributes.Add("style", "float: left; width: 370px; margin-top: 4px;");
            textBox.Text = counter.ToString();
            LeftPanel.Controls.Add(textBox);
         }
         while (counter < 13)
         {
            counter++;
            TextBox textBox = new TextBox();
            textBox.Attributes.Add("style", "float: right; width: 370px; margin-top: 4px;");
            textBox.Text = counter.ToString();
            RightPanel.Controls.Add(textBox);
         }
      }
      
      protected void Page_Load(object sender, EventArgs e)
      {
      }
   }
}

 
 

No comments:

Post a Comment