【发布时间】:2014-06-19 08:37:57
【问题描述】:
我有一个.aspx 页面,我想通过单击按钮将文本框动态添加到页面。为此,我在页面上添加了一个占位符,并在单击按钮时将控件添加到服务器端。
<asp:PlaceHolder runat="server" ID="NotificationArea"></asp:PlaceHolder>
<asp:Button ID="AddNotification" runat="server" Text="Add" OnClick="AddNotification_Click" />
<asp:Button ID="RemoveNotification" runat="server" Text="Remove" OnClick="RemoveNotification_Click" />
我将文本框存储在会话变量中,以便我可以无限期地继续添加和删除文本框。下面我放了添加和删除按钮的 on_click 方法:
protected void AddNotification_Click(object sender, EventArgs e)
{
List<TextBox> notifications = (List<TextBox>)(Session["Notifications"]);
notifications.Add(new TextBox());
notifications[notifications.Count - 1].Width = 450;
notifications[notifications.Count - 1].ID = "txtNotification" + notifications.Count;
foreach (TextBox textBox in notifications)
{
NotificationArea.Controls.Add(textBox);
}
NotificationArea.Controls.Add(notifications[notifications.Count - 1]);
Session["Notifications"] = notifications;
}
protected void RemoveNotification_Click(object sender, EventArgs e)
{
List<TextBox> notifications = (List<TextBox>)(Session["Notifications"]);
if (notifications.Count > 0)
{
NotificationArea.Controls.Remove(notifications[notifications.Count - 1]);
notifications.RemoveAt(notifications.Count - 1);
}
foreach (TextBox textBox in notifications)
{
NotificationArea.Controls.Add(textBox);
}
Session["Notifications"] = notifications;
}
这很好用。如果单击删除按钮,它会不断添加新文本框并删除最后一个文本框。然后,当我试图从文本框中获取文本时,我遇到了问题。我从来没有真正将输入到会话变量中的文本中的文本存储起来。只是最初创建的空文本框。另外,见下文:
int count = NotificationArea.Controls.Count;
调试显示 NotificationArea 中的控件计数为 0。如何访问这些动态添加的文本框控件的文本?我是否以某种方式将 ontext_change 事件添加到将特定文本框的 Text 保存到会话变量中的等效项的文本框中?我该怎么做呢?
【问题讨论】:
标签: c# asp.net dynamic textbox session-variables