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