0
我已经动态地创建了一个文本框,并且当我点击按钮时我获得了文本框的值。但是当我点击按钮时,在动态文本框中输入的值会变空。当我点击按钮时动态创建的文本框值损失
下面是我的ASPX代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Reports.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:DropDownList ID="DropDownList1" runat="server"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" AutoPostBack = "true">
<asp:ListItem>Text</asp:ListItem>
<asp:ListItem>Check</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="GetTextBoxValue" />
</form>
</body>
</html>
代码隐藏:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Reports
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox TB = new TextBox();
TB.ID = "abc";
form1.Controls.Add(TB);
Response.Write(Request.Form["abc"]);
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
createcontrol();
}
protected void createcontrol()
{
if (DropDownList1.SelectedValue.ToLower().Trim() == "text")
{
TextBox TB = new TextBox();
TB.ID = "abc";
form1.Controls.Add(TB);
}
}
}
}
这是正常的行为。当你点击按钮时,会有一个回传,并且动态添加的所有控件都会消失,并且会再次创建而没有任何价值。你可以使'Property'包含'Dictionary',Key将是创建的控件的ID,Value将是它的控制值。这个属性必须保存数据到'ViewState'或'SessionState',然后在'Update'方法中,你应该在'Page_Load'事件中将数据加载到新创建的控件上,希望这有助于 –
harry180
2012-08-14 08:46:41
[检查](http://stackoverflow.com/问题/ 7676182 /动态加载一个新文本框,在按钮点击) – 2012-08-14 08:51:13