2012-08-13 37 views
0

我已經動態地創建了一個文本框,並且當我單擊該按鈕時我正在獲取文本框的值。但是當我點擊按鈕時,在動態文本框中輸入的值會變空。當我單擊按鈕時,動態創建的文本框值不會顯示在動態Texbox中

下面是我的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); 
     } 
    } 
} 
} 

回答

1

文本框的默認保存其狀態。 EnableViewState默認爲true。

如果要保留文本值,則必須在InitLoad事件中添加TextBox

0

你應該得到你動態創建的控件,在Page_PreRender - 事件。

像這樣: //獲取值

protected void Page_PreRender(object sender, EventArgs e) { 
    //.... 
} 

但是當你創建你元素,你應該使用Page_LoadIsPostBack

this will help