Creating Controls dynamically while preserving the events handling

http://www.societopia.net/Samples/DynamicallyCreatedControls.aspx

This example was developed in response to a query on Microsoft newsgroups. Click on either the "Add a server control" or the "Add an HTML control" to create a control dynamically. However, upon postback the added controls would be lost had I not stored some information about the added controls in an ArrayList that I saved in the Session object that allows me to recreate the buttons on Page_Init and to re-wire their events.

=========================================================================

DynamicallyCreatedControls.aspx

http://www.webswapp.com/viewsource.aspx?file=/demos/DynamicallyCreatedControls.aspx

 

<%@ Page Language="C#" %>
<%@ Register TagPrefix="Societopia" tagName="PageHeader" src="PageHeader.ascx" %>
<%@ Import namespace="System.Data" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <head>
 <meta name="description"
 content="Samples in ASP.NET, C#.NET, VB.NET and web development">
 <meta name="keywords"
 content="ASP.NET, VB.NET, C#.NET, Web development, HTML, DHTML, Cascading stylesheets, Samples, WEBSWAPP, SOCIETOPIA">
 <meta name="author" content="Phillip Williams">
 <title>Societopia, ASP.NET Samples</title>
 <LINK href="Samples.css" type="text/css" rel="stylesheet">
 <style>
  .ClickedButton{Background-color:steelblue;color:white;}
 </style>
 <title>Societopia</title>
 <script language="C#" runat="server">
 private ArrayList aServerControls=null;
 private ArrayList aHTMLControls=null;
 private void Page_Init(object sender, System.EventArgs e)
 {
  if (Session["ServerControls"]!=null) aServerControls = Session["ServerControls"] as ArrayList ;
  else aServerControls = new ArrayList ();
  if (Session["HTMLControls"]!=null) aHTMLControls = Session["HTMLControls"] as ArrayList ;
  else aHTMLControls= new ArrayList ();

  foreach (string str in aServerControls)  AddNewButton(str, PH1);
  foreach (string str in aHTMLControls)  AddNewHTMLInputButton(str, PH2);
 }
 
 private void AddButton_Click(object sender, System.EventArgs e)
 {
  int count = aServerControls.Count+1;
  AddNewButton("ServerControlButton" + count, PH1);
  aServerControls.Add ("ServerControlButton" + count);
  Session["ServerControls"] = aServerControls;
 }
 private void Button_Click(object sender, System.EventArgs  e)
 {
   lblStatus1.Text="You clicked on: " + ((Button)sender).Text ;
   if (((Button)sender).CssClass =="ClickedButton")
    ((Button)sender).CssClass ="";
   else ((Button)sender).CssClass ="ClickedButton";
 }

 private void AddNewButton(string name, PlaceHolder PH)
 {
  Button NewBtn = new Button();
  NewBtn.Text = name;
  NewBtn.Click +=new EventHandler(Button_Click);
  PH.Controls.Add(NewBtn);
 }

 private void AddNewHTMLInputButton(string name, PlaceHolder PH)
 {
  System.Web.UI.HtmlControls.HtmlInputButton NewBtn = new System.Web.UI.HtmlControls.HtmlInputButton ();
  NewBtn.Value  = name;
  NewBtn.Attributes.Add("runat","server");
  //NewBtn.Attributes.Add ("onClick", "javascript:" + Page.GetPostBackEventReference(NewBtn) );
  NewBtn.ServerClick +=new EventHandler(NewBtn_ServerClick);
  PH2.Controls.Add(NewBtn);
 }
 private void AddHTMLButton_Click(object sender, System.EventArgs e)
 {
  int count = aHTMLControls.Count+1;
  AddNewHTMLInputButton("HTMLInputButton" + count, PH1);
  aHTMLControls.Add ("HTMLInputButton" + count);
  Session["HTMLControls"] = aHTMLControls;

 }

 private void NewBtn_ServerClick(object sender, EventArgs e)
 {
  lblStatus2.Text= "You clicked on: " + ((System.Web.UI.HtmlControls.HtmlInputButton)sender).Value  ;
  if (((System.Web.UI.HtmlControls.HtmlInputButton)sender).Attributes ["class"]== "ClickedButton")
   ((System.Web.UI.HtmlControls.HtmlInputButton)sender).Attributes ["class"]= "";
  else
  ((System.Web.UI.HtmlControls.HtmlInputButton)sender).Attributes ["class"]= "ClickedButton";
 }
 </script>
 </HEAD>
<body>
 
   <form runat=server ID="Form1">
 <!-- logo and menu: a user control -->
 <Societopia:PageHeader runat="server" id="PageHeader1"></Societopia:PageHeader>
 <!-- End of Logo and menu -->

 <!-----------------  begin of the body of this demo--------------------------------------------------->

 <table class="tblBody" >
 <tr>
  <td >
  <a href="http://www.webswapp.com/"><img src="webswapp.jpg"  title="WEBSWAPP stands for Web Software Applications" alt="webswapp logo"></a>
        <h3>Creating Controls dynamically while preserving the events handling</h3>
       <p>This example was developed in response to a query on Microsoft newsgroups.  Click on either the "Add a server control"
       or the "Add an HTML control" to create a control dynamically.  However, upon postback the added controls would be lost had I
       not stored some information about the added controls in an ArrayList that I saved in
       the Session object that allows me to recreate the buttons on Page_Init and to re-wire their
       events.</p>

     <asp:Button ID="btn1" Runat="server" Text="Add a server control: Button" OnClick="AddButton_Click"></asp:Button>
     <asp:Button ID="btn2" Runat="server" Text="Add an HTML Control" OnClick ="AddHTMLButton_Click"></asp:Button>
     <hr>
     <p>Server controls</p>
     <asp:PlaceHolder ID="PH1" runat="server"></asp:PlaceHolder>
     <asp:Label ID="lblStatus1" Runat=server ></asp:Label>
     <hr>
     <p>HTML Controls</p>
     <asp:PlaceHolder ID="PH2" Runat="server"></asp:PlaceHolder>
     <asp:Label ID="lblStatus2" Runat=server ></asp:Label>
  </td>
 </tr>
 <!--------------------------------------------- page footer -------------------------------------------------------->
 <tr>
  <td class="footer" >
   <p>Source Code</p>
   <ol>
          <li><a href="http://www.webswapp.com/viewsource.aspx?file=/demos/DynamicallyCreatedControls.aspx">DynamicallyCreatedControls.aspx</a></li>
         </ol>
  </td>
 </tr>
 </table>

   </form>
</body>

 

=====================================================

Title Plateform Description
2-way Databinding of dependent dropdownlists in a FormView C#, ASP.NET 2.0 In this sample I deal with the problem of 2-way databinding dependent lists to avoid the error message: "Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control"
  • Displaying Dates in different cultural formats C#, ASP.NET 2.0 In this demo I use ASP.NET2.0 new features: Culture="auto" UICulture="auto" which are attributes to be added to the page directive. When you enter the screen your browser settings would determine the language in which the Calender is displyed. You can also change it to a specific culture using a dropdownlist
  • Nested datagrids (both editable) C#, ASP.NET 1.1 In this demo I represent a parent-child tables relation (company table that has the company name and address related to the Employees table that has the employees information). The purpose is to represent the employees per company in an editable format where you can edit both the company (summary info) and the employees (detail info) records.
  • Draw images using System.Drawing library C#, ASP.NET 1.1 In this sample I I create a high-resolution bitmap object. I clear its background color, draw a polygon and fill it with a color then draw a text.
  • Report of Hierarchical data using DataLists C#, ASP.NET 1.1 In this demo I deal with the case of reporting hierarchical data using the DataList server control.
  • Report of Hierarchical data using Repeaters C#, ASP.NET 1.1 In this demo I deal with the case of reporting hierarchical data using the Repeater server control.
  • Dynamically Created Controls C#, ASP.NET 1.1 In this demo I deal with the case when you have to create your server controls within the handling of another server control event.
  • DataGrid dynamically created Columns VB, ASP.NET 1.1 When you have to display an undetermined number of columns on a datagrid, you can use dynamic template creation.
  • Pivoting a DataGrid Javascript, C#, ASP.NET 1.1 Transposing the matrix rendered by a datagrid control using client-side Javascript.
  • Declaratively nested User Controls (ascx) VB, ASP.NET 1.1 This sample uses event delegates to capture the events triggered by declaratively-created controls nested within a Datagrid. In this sample I have a textbox and a dropdownlist as a user control. Using event delegates the client of the datagrid control (the page) can handle the events raised by the user control that passes customized information through the event arguments.
  • Dynamically Created Controls in a DataGrid C#, ASP.NET 1.1 This sample uses event delegates to capture the events triggered by controls nested within a Datagrid. In this sample I have checkboxes and dropdownlists. Using event delegates the client of the datagrid control can process those events.
  • Dropdownlists nested in a Datagrid C#, ASP.NET 1.1 In one scenario dropdownlist is created in the ItemTemplate and causes a postback that gets the itemIndex of the grid row and then selects that row. In the other the dropdownlist is only created within the EditItemTemplate, i.e. only appears upon editing, which is the most expected way for using the dropdownlist within a datagrid.
  • How to use the Enter keypress to submit different sections on a web page VB, Javascript, ASP.NET 1.1 In this demo you have several areas on the page, each has a separate submit button. By associating every textbox control with a specific button using javascript onKeyPress (or onKeyDown) you can specify which button will submit the form based on the textbox where the Enter key was pressed.
  • Fixed Header on an updatable DataGrid with multiple primary keys C#, CSS, Javascript, ASP.NET 1.1 In this sample I used CSS to fix the header on the datagid. This sample also displays a parent child relationship on 2 separate datagrids using multiple primary keys. You drill into the details by a click on the parent grid rows
  • Copy and paste fields on datagrid using client-side scripting VB, Javascript, ASP.NET 1.1 This sample displays 2 tables based on primary and foriegn keys. It also uses Javascript to copy values on the client that can update the DataTable.
  • DataGrid Default paging with custom navigation controls C#, ASP.NET 1.1 In this sample I create navigation buttons: First, next, previous and last.
  • Hyperlinkcolumn to expand the detail of a DataGrid row C#, Javascript, ASP.NET 1.1 Display of a parent child relation on 2 separate datagrids
  • HTMLTable Hierarchical data representation VB, Javascript, ASP.NET 1.1 In this sample I used HTMLtables and managed their ViewState to get an effect similar to datagrids
  • DataGrid Hierarchical data representation VB, Javascript, ASP.NET 1.1 In this sample I used DataGrids
  • Dropdownlist C#, Javascript, ASP.NET 1.1 In this demo I disable and hide any item of the dropdown list based on the user's selection
  • DataBound Textbox VB, Javascript, ASP.NET 1.1 This is a text box that takes care of updating its value. It also needs the user to type only the first characters of their entry then it would pick up the matching record from the databound datasource
  • TextBox with intellisense using client-side scripting and XML/XSL VB, Javascript, ASP.NET 1.1 This control is useful for representing repeated data on the same page. For example in many applications you might have a page with several dropdownlist for the City/Country (once for the origin then again for the destination). If you use the regular control this would create a large page with a big ViewState. To avoid that I use an XML file that contains the city/Country information and render a dynamically generated HTML div tag to simulate a dropdown list.
  • DataGrid nested within another templated control VB, Javascript, ASP.NET 1.1 In this case I used the datalist as the parent control. This sample demonstrates how to use the ItemDataBound event to create effects such as highlighting the row on hovering over, and performing an action when you click on any place on the grid row (in this case I used the Hyperlink in the first column to supply the action be done when clicking on the row
  • DataGrid within a datalist VB, Javascript, ASP.NET 1.1 This is another variation of the preceding demo where clicking on any row would execute the javascript:document.URL directly without using a post back (from the Hyperlink button)
  • Datagrid Simple demo VB, Javascript, ASP.NET 1.1 In this demo I make a simple formatted editable datagrid. I also use standard paging on the datagrid and use javascript to set the focus to the edit box in the edittemplate
  • Using Javascript to update grid item cells on the client VB, Javascript, ASP.NET 1.1 In this example I update a column on the datagrid that is not databound to any field on the client-side using Javascript. I manage the state of the copied item and later upon postback I update the appropriate datafields.
  • Using a page able datagrid within a repeater VB, Javascript, ASP.NET 1.1 In this example I place a pageable datagrid nested within a repeater.
  • Applying Cascading Style Sheets to a DataGrid VB, Javascript, CSS, ASP.NET 1.1 Cascading style sheets can help define not only a general style for the entire datagrid but also to specify individual columns' styles by specifying a cssClass for each DataBoundColumn. In this example the textbox size, the background-color and the font are different for each column that overrides the default cssClass settings for the datagrid
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值