Bhushan Gupta

Bhushan Gupta

  • NA
  • 383
  • 3.6k

How to add and delete controls dynamically on runtime ?

Mar 25 2014 8:33 AM
Adding code is working proper but how to delete ?
 
%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div style ="width:200px">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Button ID="Button1" runat="server" Text="Add Textbox" OnClick="add_Click" />
</div>
</form>
</body>
</html> 
 
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["AddControl"] = 1;
}
}
protected void add_Click(object sender, EventArgs e)
{
add_button(Convert.ToInt32(ViewState["AddControl"]));
}

protected void add_button(int i)
{
for (int j = 0; j < i; j++)
{
TextBox textbox_foradd = new TextBox();
textbox_foradd.ID = "textadd" + (j + 1).ToString();
PlaceHolder1.Controls.Add(textbox_foradd);

Button btn = new Button();
btn.Text = "X";

textbox_foradd.ID = "btn" + (j + 1).ToString();
PlaceHolder1.Controls.Add(btn);
}
ViewState["AddControl"] = i + 1;
}

Answers (2)