[英]How to (C#) : Dynamically Create multiple controls on add click and access their properties
我只想在“添加”按鈕的每個單擊事件上添加文本框控件。 如何為在運行時動態創建的每個控件實現事件處理程序,然后從事件處理程序訪問其屬性。
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);
}
}
但是無法訪問新添加的文本框的Text屬性。 如果有人可以幫助我,我將不勝感激。
使用此代碼
用於動態添加文本框
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++;
}
}
獲取動態創建的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代碼
<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" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.