0

I wrote this code in .NET. When I want to change ‘s’ by clicking button2, it doesn’t change. I mean after clicking button2 and then I click Button1 to see the changes but nothing changes. How can I change and access the value of ‘s’ properly. What am I doing wrong?

public string s;

public void Button1_Click(object sender, EventArgs e)
{
    Label1.Text = s;
}

public void Button2_Click(object sender, EventArgs e)
{
    s = TextBox1.Text;  
}
4

1 回答 1

3

您需要了解 Web 应用程序是如何工作的。

在每次回发中,都会加载处理页面的类的实例,因此当您单击按钮 1 时,页面会回发并再次加载,因此变量 s 不会与您的内容一起加载。

要使此代码正常工作,您需要将 S 值保存在页面视图状态中。

尝试替换“公共字符串 s;” 有了这个:

public string s
{
    get {  return (string)ViewState["myValue"]; }
    set [ ViewState["myValue"] = value };

}

有关页面生命周期的更多信息,请访问:http: //msdn.microsoft.com/en-us/library/ms178472 (v=vs.100).aspx

于 2013-07-25T13:39:11.463 回答