我回发时如何从ViewState执行Textbox值?

时间:2013-04-02 12:51:45

标签: c# asp.net .net viewstate

  

我想知道如何从ViewState中追溯Textbox的值。

由于Textbox click 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";
}

1 个答案:

答案 0 :(得分: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方法中,如果它不是回发并且为null,则将创建一个ViewState。在写完您的视图状态文本框后,在Button1_Click中,您将新的textbox1添加到视图状态。