Dynamically removing controls

Hi all,

My problem is pretty simple: I want to be able to click + and - buttons to add or remove text boxes. Adding works fine but when removing you have to click on the button twice. I've searched around and seen the same issue elsewhere but somehow I'm not quite able to grasp what changes I need to make to my own code. Any help would be greatly appreciated.

Here's the aspx file contents:

<%@ Page language="c#" Codebehind="AddingDropdowns.aspx.cs" AutoEventWireup="false" Inherits="ARD.Dev.Assets.AddingDropdowns"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
  <head>
    <title>AddingDropdowns</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">
      <asp:Button id="AddDropdown" runat="server" Text="+"></asp:Button><asp:Button id="RemoveDropdown" runat="server" Text="-"></asp:Button>
      <div id="DropdownPanel" runat="server"></div>
    </form>
  </body>
</html>

and here's the code:


namespace ARD.Dev.Assets
{
 /// <summary>
 /// Summary description for AddingDropdowns.
 /// </summary>
 public class AddingDropdowns : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.Button AddDropdown;
  protected System.Web.UI.WebControls.Button RemoveDropdown;
  protected System.Web.UI.HtmlControls.HtmlGenericControl DropdownPanel;
 
  // structure to store info about a control
  private struct ControlInfo
  {
   public string ID;
   public string Type;
  }
  private void Page_Load(object sender, System.EventArgs e)
  {
  }
  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: This call is required by the ASP.NET Web Form Designer.
   //
   ShowPersistantControls();
   InitializeComponent();
   base.OnInit(e);
  }
  
  private void ShowPersistantControls()
  {
   if (!this.IsPostBack)
   {
    // initialize controls number
    // used to create control id
    Session.Add("LastControl", 1);
    CreatePersistantControl("DropDownList" + Session["LastControl"], "DropDownList");
    Session["LastControl"] = (int)Session["LastControl"] + 1;
   }
   else
   {
    // recreate controls created on previous roundtrips
    RecreatePersistedControls();
   }
  }
  private void InitializeComponent()
  {   
   this.AddDropdown.Click += new System.EventHandler(this.AddDropdown_Click);
   this.RemoveDropdown.Click += new System.EventHandler(this.RemoveDropdown_Click);
   this.Load += new System.EventHandler(this.Page_Load);
  }
  #endregion
  private void RecreatePersistedControls()
  {
   ArrayList al = (ArrayList)this.Session["DynamicControls"];
   if (al != null)
   {
    foreach(ControlInfo ci in al)
    {
     this.CreateControl(ci);
    }
   }
  }
  private Control CreateControl(ControlInfo ci)
  {
   Control ctl = null;
   switch(ci.Type)
   {
    case "TextBox":
     ctl = new TextBox();
     break;
    case "DropDownList":
     ctl = new DropDownList();
     break;
   }
   
   ctl.ID = ci.ID;
   this.DropdownPanel.Controls.Add(new LiteralControl(ctl.ID));
   this.DropdownPanel.Controls.Add(ctl);
   this.DropdownPanel.Controls.Add(new LiteralControl("<br />" + Environment.NewLine));
   return ctl;
  }
  
  private ControlInfo PersistControl(string id, string type)
  {
   ControlInfo ci = new ControlInfo();
   ci.ID = id;
   ci.Type = type;
   ArrayList al = (ArrayList)this.Session["DynamicControls"];
   if (al == null)
   {
    al = new ArrayList();
   }
   al.Add(ci);
   this.Session["DynamicControls"] = al;
   return ci;
  }
  private void CreatePersistantControl(string id, string type)
  {
   ControlInfo NewControlInfo = new ControlInfo();
   NewControlInfo.ID = id;
   NewControlInfo.Type = type;
   CreateControl(NewControlInfo);
   PersistControl(id, type);
  }
  private void AddDropdown_Click(object sender, System.EventArgs e)
  {
   if (Session["LastControl"] == null)
   {
    Session["LastControl"] = 1;
   }
   CreatePersistantControl("DropDownList" + Session["LastControl"], "DropDownList");
   Session["LastControl"] = (int)Session["LastControl"] + 1;
  }
  private void RemoveDropdown_Click(object sender, System.EventArgs e)
  {
   ArrayList al = (ArrayList)this.Session["DynamicControls"];
   ControlCollection cc = DropdownPanel.Controls;
   // if there's at least one control in the DynamicControls session variable,
   // remove the last control
   if (al != null && al.Count > 1 && cc.Count > 1)
   {
    al.RemoveAt(al.Count - 1);
    cc.RemoveAt(DropdownPanel.Controls.Count - 1);
    Session["LastControl"] = (int)Session["LastControl"] - 1;
   }
  }
 }
}
0
rmf
5/23/2005 9:05:36 PM
asp.net.web-forms 93655 articles. 5 followers. Follow

0 Replies
487 Views

Similar Articles

[PageSpeed] 23

Reply:

Similar Artilces:

Dynamic Slave Controls
I am working a solution to enhance slave controls. I have created a proof of concept based on the 2.04 code base that shows how to load slave controls without switching to the admin view. I have included a sample module that contains 3 view controls. Each control has a row of buttons that can be used to load one of the other 2 controls. (and no I am not using panels.) The default control has a drop down of other instances of the dynamic control that exist on the current tab. Using the module communicator you can raise an event from one control that tells another instance of the module what c...

Controlling web control instances on Web Form
I have created a composite control, extending functionality of the Hidden Control. However, I would like to prevent the user from adding this control to the page multiple times. I only want one instance of the control on the Web Form. What setting in my project to I adjust to enable this functionality? I can not find it in any of the books that I have referenced. Is this a setting or is this code that has to be added to the inheriting class. Looks like there is no standard apporach. But I'd consider using static field to count number of created objects and throw exception if second object ...

Problem in accessing web form data in user controls when create user control dynamically
HI. I have a problem using web user control. I designed a user control named NewsForm. This user control contains some web form elements like <asp:textbox>. When I add it in an .ASPX page, all things may be true. I can know which user filles in textbox (for example and other controls) <%@ Register TagPrefix="uc1" TagName="NewsForm" Src="NewsForm.ascx" %> and <UC1:NewsForm id="newsForm" runat="server"></UC1:NewsForm> But when i create it in code behined dynamically, however user control has web form controls but their value are blank for example //aspx co...

How to access a control on a web form from anoter web form
hi all I have this scenarios i have two web forms, one called form1 and the other called form2 form1 has a label with id "lbl1" is it possible to access lbl1 from form2, change its text permenantly? thanks.   refer: http://dotnetslackers.com/Community/blogs/haissam/archive/2007/11/26/ways-to-pass-data-between-webforms.aspxSSNPlease remember to click "Mark as Answer" on the post that helps you. MinaSamy: hi all I have this scenarios i have two web forms, one called form1 and the other called form2 form1 has a label with id "lbl1" is it p...

Web Form Dynamic Control
Hello, I have a web form using .net 2.0.  When the user finishes entering in information it is mailed.  This works fine. Now I need to be able to dynmaicly add addtional controls. Basicly have a "Add Additonal Names" button, when user clicks this a row and cells are added to the webform table, and two textoboxes and a radiobutton list is added. What is the best way to do this?   -TFTH Bryan The easiest way is to place the controls on the page and set their visible value to false. Then in the button click event change their state to visible. The visible var in a contro...

how to call controls of web control form in coding of other forms?
hello everyone i have one problem i have created one webcontrol shoppingcart in which there are two labels one of qty and other of amt which are initially enable =falsenow on other page(aspx page) i have one txtbox of qty as txtqty i want tat as soon as user enters qty txtqty and clicks on add cart button it shd be display d value in lblqty of web control shopping cart make sure i m using datalist on aspx page so give me suggestions on tat basis and my coding is in vb. plz give ur suggestions as fast as possible. Neeti what do you mean by webcontrol.... it this user control or normal ...

Dynamically created controls in web form
Hi there. This is bit of an open ASP.Net (C#) question with regards to dynamically created controls and in particular tabular or panel controls. What I currently have is a web page that creates between 1 and 6  tables, each of which holds specific data about a set of products, each table (or panel, if you want) has a couple of multi-line TextBoxes and a few other controls, all lined up in a set format. The number is determined by the data records returned from a database table. My question is what is a best way to create these tables of data at run time?  Has anybody else had e...

Dynamically add control to web form
Hi, How can I add controls dynamically to the web form on run time.I have button called 'Add more controls'. When I click this button the code should generate one control(textbox, or Dropdownlist) to the form.If I click this button again it should add one more control to the page etc.How I can achieve this functionality? Thanks.. You could always add the control to the form at runtime and set the visibility to false. When you click the button you want to to add the control to the page, just set the visibility property of the control to true.Erin...

Dynamically creating controls in Web forms
I am able to create a web control programmatically and display on the form. In the click event of the button then I am trying to capture the value entered in the above created textbox in another click of button but I am unable to obtain the reference of the control that has been created dynamically. Can anyone help me please? protected System.Web.UI.WebControls.Panel myPanel; private void btnMake_Click(object sender, System.EventArgs e) { TextBox txtBox = new TextBox(); myPanel.Controls.Add(txtBox); } private void btnGotValues_Click(object sender, System...

.Net Windows Control in Web Form
Hi all,How can I use a .Net windows control in a web form? I use object tag but it doesn't work and displays empty.Thanks in advance cheers Hi, you can check this article out: Hosting a Windows Control in a Web Form. This shows only how to host the control. If you want interaction with the client you can do this by setting the correct CAS (Code Access Security) settings on the client pc. Grz, Kris.Read my blog. Handy Firefox plugins for web developers.Workaround for non working Mark as answer buttons. Thanks guys for your replycheers...

Implementing .Net Form into an APS.net web form, can this be done
I am new here, but have been searching for a while, and may not have the correct lingo to find what I am looking for.  I am tasked with implementing a .exe application that was writen vb6 then converted to .net into a new website my team is developing. The idea is to put each of the 3 different forms in this .exe application of 3 different .aspx pages. I have attempted multiple things to get this into the page and even started to just rewrite it as an ASP.net web form, but even then I can't reuse any of the code since the System.Web.UI.Page doesn't inherit the sa...

Can you return .net web controls in a .net page from a web service?
I've got a problem with a project. I've got to compile an entire .net page and return it as part of a Web Service for display. The problem I have is that I need to add WebControls and functionality to the page so that not only the html content and images are displayed (which I've managed) but that textboxes, labels, buttons and datasets can be displayed also. Essentially I need to make a call from one site for a page, populate the page and return it in a state as though it resided on the same server/webspace as the calling page. Code is currently built as follows into a string: strOpenHT...

Dynamic Generation of Web Forms in C#.net
I am new to c# and vs.net studio as such and am seekin help for my project. It deals with generating webforms at runtime by takin in inputs from the user. The user will input no. of webfroms to be generated and all the attributes he want in them. I have got the datamodel right for this where all the info by the user is stored in sql server database. During runtime my application should read it from that database and based upon that generated these .aspx forms which can be posted online for use. I think it would help if you explained what the application would accomplish. It sounds like yo...

dynamically creating html controls on web form
hello all, I'm creating html <input type="file" name="test" id="test" runat="server"> dynamically using Javascript on a .aspx page. when i submit the form i get Javascript "Access is denied" error. if i take out name attribute from input tag in javascript -  it is not throwing any javascript error but the file is not being uploaded to the server. Can anyone point me in the right direction? Thanx in advance     Maybe this is a security restriction imposed by the browser? I know there are several constrain...

Looping through controls in VB.Net Web Form
I need to disable every imagebutton. In VB6, I would have done it like this: 1 Dim iButton As ImageButton 2 For Each iButton In Me.Controls 3 iButton.Enabled = False 4 Next In .Net, I get a "Specified cast is not valid" errror on line 2. Using Page.controls in place of Me.Controls also produces the same error. So, I tried this (and multiple variations): 1 Dim ibControl As Object 2 For Each ibControl In Me.Controls 3 If TypeOf ibControl Is ImageButton Then 4 ...

Web resources about - Dynamically removing controls - asp.net.web-forms

iPhone 5 A6 chip to dynamically up-clock up to 1.3GHz (and downclock too)?
Interesting video from our friends at TLDToday: If this is not just a Geekbench app glitch, it could indicate why that A6 processor is so 2X ...

Apple's Lightning port dynamically assigns pins to allow for reversible use
... a closer look at how Apple's new Lightning connector works, and has come to the conclusion that the 8 pins on each side of the plug are dynamically ...

iPhone 5 Lightning port dynamically reassigns pins
... of Apple's Lightning USB cable shows that the pins on the plug aren't arranged symmetrically, suggesting that the Lightning port can dynamically ...

Urlbox Launches Screenshots-as-a-Service Platform to Dynamically Update Galleries
... changes. Launched yesterday, Urlbox allows anyone with a gallery displaying website screenshots to automate the process and keep them dynamically ...

Everything.me launcher dynamically adapts to what you’re doing right now
... phone according to what you’re doing. Perform a search for ‘football’ and your background will change to the NFL logo. A launcher that dynamically ...


A YouTube Experiment Resizes the Player Dynamically
There's a new YouTube experiment that changes the video player's size, depending on the browser window's size. When resizing Chrome's window, ...

Apple Granted “Dynamically Changing Cursor for User Interface” Patent, Originally Filed in 2003
... a utility patent that covers the use of the mouse cursor that changes according to the context of the task it is engaged in. Called a “Dynamically ...

Atmel's FPSLIC II Dynamically Reconfigurable SoC Supports "Silicon-Sharing" For Peripherals & Interfaces ...
Silicon-Sharing Fits 200K Gate Design into 40K Gate FPSLIC II's, Cuts Power Drain by 97%

Everything.me Launcher Wants to Dynamically Change Phones Based on Location, Interests, and Mental State ...
What if your phone’s launcher dynamically changed based upon interests, your location, or topics you had in mind at a specific moment? A new ...

Resources last updated: 1/7/2016 7:41:26 AM