I just want to add Text box control on each click event of Add button. How do I implement event handler for each controls created dynamically at runtime and then Access their properties from Event Handler.
C#
static int counter = 0;
protected void addMore_Click(object sender, EventArgs e)
{
counter++;
for (int j = 1; j <= counter; j++)
{
TextBox tb = new TextBox();
Button btn = new Button();
tb.ID = "Tb" + counter;
// tb.TextChanged += new System.EventHandler(tb_TextChanged);
btn.ID = "btn" + counter;
btn.Text = "Remove";
PlaceHolder1.Controls.Add(tb);
PlaceHolder1.Controls.Add(btn);
}
}
But not able to access Text property of newly added textboxes. Would really appreciate if someone could help me..
Use this code
For adding text box dynamicaly
protected void AddTextBox(object sender, EventArgs e)
{
int index = pnlTextBoxes.Controls.OfType<TextBox>().ToList().Count + 1;
this.CreateTextBox("txtDynamic" + index);
}
private void CreateTextBox(string id)
{
TextBox txt = new TextBox();
txt.ID = id;
pnlTextBoxes.Controls.Add(txt);
Literal lt = new Literal();
lt.Text = "<br />";
pnlTextBoxes.Controls.Add(lt);
}
protected void Page_PreInit(object sender, EventArgs e)
{
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("txtDynamic")).ToList();
int i = 1;
foreach (string key in keys)
{
this.CreateTextBox("txtDynamic" + i);
i++;
}
}
Getting values of dynamically created TextBoxes
protected void GetTextBoxValues(object sender, EventArgs e)
{
string message = "";
foreach (TextBox textBox in pnlTextBoxes.Controls.OfType<TextBox>())
{
message += textBox.ID + ": " + textBox.Text + "\\n";
}
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('" + message + "');", true);
}
ASP Code
<asp:Panel ID="pnlTextBoxes" runat="server">
</asp:Panel>
<hr />
<asp:Button ID="btnAdd" runat="server" Text="Add New" OnClick="AddTextBox" />
<asp:Button ID="btnGet" runat="server" Text="Get Values" OnClick="GetTextBoxValues" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.