单击按钮时动态添加的文本框为空
本文关键字:文本 添加 按钮 动态 单击 | 更新日期: 2023-09-27 18:21:57
我正在动态添加TextBoxes,当我单击提交按钮并进行回发时,我看不到输入到TextBoxes中的值,所有值都会出现emtpy。这是.aspx页面…''
form id="form1" runat="server">
<asp:PlaceHolder ID="phFormContent" runat="server">
</asp:PlaceHolder>
<br /><br />
<asp:Button ID="btnAddForm" runat="server" Text="Add Form" OnClick="btnAddForm_Click" />
<asp:Button ID="btnSubmitForms" runat="server" Text="Submit Forms" OnClick="btnSubmit_Click" />
</form>
以下是我如何在单击"添加表单"时将文本框添加到表单中。。。
protected void btnAddForm_Click(object sender, EventArgs e)
{
// Create Labels
Label lblName = new Label();
lblName.Text = "NAME:";
Label lblNumber = new Label();
lblNumber.Text = "NUMBER:";
Label lblAddress = new Label();
lblAddress.Text = "ADDRESS:";
Label lblCompany = new Label();
lblCompany.Text = "COMPANY:";
// Create Text Boxes
TextBox txtName = new TextBox();
TextBox txtNumber = new TextBox();
TextBox txtAddress = new TextBox();
TextBox txtCompany = new TextBox();
// Create submit button
Button btnSubmit = new Button();
btnSubmit.Text = "SUBMIT";
// Create panel and add controls
Panel pnlForm = new Panel();
pnlForm.Controls.Add(lblName);
pnlForm.Controls.Add(txtName);
pnlForm.Controls.Add(new LiteralControl("<br /><br />"));
pnlForm.Controls.Add(lblNumber);
pnlForm.Controls.Add(txtNumber);
pnlForm.Controls.Add(new LiteralControl("<br /><br />"));
pnlForm.Controls.Add(lblAddress);
pnlForm.Controls.Add(txtAddress);
pnlForm.Controls.Add(new LiteralControl("<br /><br />"));
pnlForm.Controls.Add(lblCompany);
pnlForm.Controls.Add(txtCompany);
pnlForm.Controls.Add(new LiteralControl("<hr />"));
pnlForm.Controls.Add(new LiteralControl("<br /><br />"));
panels.Add(pnlForm);
foreach (Control panel in panels)
{
phFormContent.Controls.Add(panel);
}
}
下面是我如何提取每个单独添加的面板的字段。。。
private static void GetFormFields(Control panelControl)
{
ControlCollection controls = panelControl.Controls;
foreach (Control childControl in panelControl.Controls)
{
if (childControl.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
{
TextBox txt = childControl as TextBox;
fields.Add(txt);
}
else
{
GetFormFields(childControl);
}
}
}
面板和字段是静态列表,每个面板包含四个字段。我向GetFormFields传递一个单独的面板引用。。。
private static List<Control> panels = new List<Control>();
private static List<TextBox> fields = new List<TextBox>();
尝试在Page_Init
事件上动态添加它们。通常,这将确保它们在PostBack
中持续存在。如果你不能做到这一点,你将不得不考虑通过存储在ViewState
中手动保存他们的数据。
看起来文本框没有包含在页面的VIEWSTATE中,因此在回发时丢失。
这里有一些关于这种情况下会发生什么的细节:
http://msdn.microsoft.com/en-us/library/kyt0fzt1(v=VS.71).aspx