我有一个.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;
}
这很好用。如果单击“删除”按钮,它会不断添加新文本框并删除最后一个文本框。然后,当我试图从文本框中获取文本时,我遇到了一个问题。我从未在会话变量中实际存储键入textboces的文本。只是最初创建的空文本框。另外,见下文:
int count = NotificationArea.Controls.Count;
调试此显示NotificationArea中控件的计数为0.如何访问这些动态添加的文本框控件的文本?我是否以某种方式将ontext_change事件添加到文本框中,以便将特定文本框的Text
保存到会话变量中的等效文件中?我该怎么做呢?
答案 0 :(得分:0)
找到解决方案here。事实证明,您需要重新创建在每个帖子上动态添加的所有控件
public void Page_Init(object sender, EventArgs e)
{
CreateDynamicControls();
}
private void CreateDynamicControls()
{
notifications = (List<TextBox>)(Session["Notifications"]);
if (notifications != null)
{
foreach (TextBox textBox in notifications)
{
NotificationArea.Controls.Add(textBox);
}
}
}
这样做可以让我随时访问这些控件的内容。