2012-08-14 35 views
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); 
     } 
    } 
} 
} 
+0

這是正常的行爲。當你點擊按鈕時,會有一個回傳,並且動態添加的所有控件都會消失,並且會再次創建而沒有任何價值。你可以使'Property'包含'Dictionary ',Key將是創建的控件的ID,Value將是它的控制值。這個屬性必須保存數據到'ViewState'或'SessionState',然後在'Update'方法中,你應該在'Page_Load'事件中將數據加載到新創建的控件上,希望這有助於 – harry180 2012-08-14 08:46:41

+0

[檢查](http://stackoverflow.com/問題/ 7676182 /動態加載一個新文本框,在按鈕點擊) – 2012-08-14 08:51:13

回答

2

當您在.NET中使用動態控件,並希望它們的值回發後訪問您需要創建它們在頁面的Page_Init方法中。本質上它不工作,因爲ViewState已經在您創建控件時被設置。有關此主題的詳細信息,請參閱本指南http://www.4guysfromrolla.com/articles/081402-1.aspx。要解決這個問題,請將Textbox實例化代碼提升到Page_Init方法,並且一切都會很好。

相關問題