2013-04-02 61 views
0

我想知道如何從ViewState中追蹤文本框的值。如何在我回發時從ViewState執行Textbox值?

作爲用戶輸入任何值Textboxclick submit button由於postbackTextbox值消失,

但是,如果我在這種情況下使用ViewState,然後是有任何方式看到或顯示從Viewstate該值?

<html> 
<body> 
    <form id="form1" runat="server"> 
     <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
     <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"/
    </form> 
</body> 
</html> 

protected void Button1_Click(object sender, EventArgs e) 
{ 
    TextBox1.Text += "X"; 
} 
+2

只要從控件中獲取它,那就是ViewState所做的事情:確保控件被預先填充。 –

+1

我假設你在'Page_Load'中有這樣的代碼:'TextBox1.Text =「initialvalue」;'。如果是這樣,將它包裝在'if(!IsPostBack){// ...}' –

+0

是的它是在裏面如果(!IsPostBack){// ...} – Neo

回答

1

在您的網頁加載使用此。

protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
     { 
      if (ViewState["Values"] == null) 
      { 
       ViewState["Values"] = new string(); 
      } 
     } 

     TextBox1.Text = ViewState["Values"].ToString(); 
    } 

在使用之後。

protected void Button1_Click(object sender, EventArgs e) 
    { 
     ViewState["Values"] += TextBox1.Text; 
    } 

在第一Page_Load方法,您將創建一個視圖狀態,如果它不是一個回傳和空。之後,將文本框寫入您的視圖狀態,在Button1_Click中,您將添加新的textbox1到您的視圖狀態。

相關問題