我想在ASP.NET動態創建文本框時增加額外的一個,我的代碼不工作,我希望它的方式......動態創建文本框,每當用戶點擊一個按鈕
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public int TextBoxCount
{
get
{
if (ViewState["tbCount"] == null)
{
ViewState["tbCount"] = 0;
}
return Convert.ToInt32(ViewState["tbCount"]);
}
set
{
int viewState = TextBoxCount;
if (Int32.TryParse(value.ToString(), out viewState))
{
ViewState["tbCount"] = value;
}
}
}
protected void Page_Init(object sender, EventArgs e)
{
if (TextBoxCount == 0)
{
AddTextBox();
}
else
{
RecreateTextBoxes();
}
}
private void AddTextBox()
{
TextBox tb = new TextBox();
tb.ID = "tb" + TextBoxCount++;
Panel1.Controls.Add(tb);
}
private void RecreateTextBoxes()
{
for (int i = 0; i < TextBoxCount; i++)
{
TextBox tb = new TextBox();
tb.ID = "tb" + i;
Panel1.Controls.Add(tb);
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
AddTextBox();
}
protected void btnDisplayText_Click(object sender, EventArgs e)
{
for (int i = 0; i < TextBoxCount; i++)
{
TextBox tb = (TextBox)Page.FindControl("Panel1").FindControl("tb" + i);
if (tb != null)
{
lblText.Text += "," + tb.Text;
}
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="lblText" runat="server" />
<div>
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
</div>
<asp:Button ID="btnDisplayText" runat="server" Text="Display Text" onclick="btnDisplayText_Click" />
<asp:Button ID="btnAdd" runat="server" Text="Add" onclick="btnAdd_Click" />
</form>
</body>
</html>
我所試圖做的是動態創建一個新的文本框每個用戶點擊按鈕btnAdd
時間。然後btnDisplayText
按鈕應串聯的所有文本中的每個文本框和lblText
顯示。
感謝您的幫助!
你讓我們知道發生了什麼 - 即使它不是你的願望是什麼? –