I have created this article for Visual Studio 2012. Let’s begin. First, create a new Empty WebSite. Add a web form to the application.
Now add the following code in the aspx page,
- <div>
- <div>
- <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Images/plus.png" CssClass="wdth" OnClick="ImageButton1_Click" />
- </div>
- <div>
- <asp:PlaceHolder ID="PlaceHolder1" runat="server">
- <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
- </asp:PlaceHolder>
- </div>
- </div>
Now in the code behind add the following code,
- TextBox tb;
- ImageButton ImgBtn;
- static int i = 0;
- protected void Page_Load(object sender, EventArgs e) {
- if (!IsPostBack) {
- i = 0;
- }
- }
- protected void CreateControls(int L) {
- tb = new TextBox();
- tb.ID = "TxtDynamic" + L.ToString();
- ImgBtn = new ImageButton();
- ImgBtn.ID = "ImgBtn" + L.ToString();
- ImgBtn.ImageUrl = "~/Images/minus.png";
- ImgBtn.CssClass = "wdth";
- ImgBtn.Click += ImgBtn_Click;
- PlaceHolder1.Controls.Add(tb);
- PlaceHolder1.Controls.Add(new LiteralControl(" "));
- PlaceHolder1.Controls.Add(ImgBtn);
- PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
- }
- protected void ImageButton1_Click(object sender, ImageClickEventArgs e) {
- for (int j = 0; j <= i; j++) {
- CreateControls(j);
- }
- i++;
- }
- private void ImgBtn_Click(object sender, ImageClickEventArgs e) {
- ImageButton MyImgBtn = (sender as ImageButton);
- MessageBox(MyImgBtn.ID.ToString());
- char last = MyImgBtn.ID.ToString()[MyImgBtn.ID.ToString().Length - 1];
- string txtbxid = "TxtDynamic" + last;
- MessageBox(txtbxid);
- TextBox ctlTextbox = (TextBox) PlaceHolder1.FindControl(txtbxid);
- MessageBox(ctlTextbox.Text);
- PlaceHolder1.Controls.Remove(ctlTextbox);
- PlaceHolder1.Controls.Remove(MyImgBtn);
- i--;
- }
- private void MessageBox(string msg) {
- Label lbl = new Label();
- lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
- Page.Controls.Add(lbl);
- }
-
- protected void Page_PreInit(object sender, EventArgs e) {
- List < string > keys = Request.Form.AllKeys.Where(key => key.Contains("TxtDynamic")).ToList();
- int k = 1;
- foreach(string key in keys) {
- this.CreateControls(k);
- k++;
- }
- }
-
Most of the code is self explanatory.
You can download the attached solution and work on it yourself. Thank you.