我尝试在方法中设置一个值,如下所示,但是当我运行 btnSaveValue 时,没有要检索的值。我什至尝试在默认类中创建一个私有(private) int val 并将值分配给它,但仍然出现一个空白值 - 谁能帮助我?
谢谢
public partial class _Default : System.Web.UI.Page
{
valueAllocation valAlloc = new valueAllocation();
public void declaringValue()
{
valAlloc.setValue(5);
int testAlloc = valAlloc.getValue();
lblResult.Text="Value set here is:"+testAlloc; //THIS WORKS!!!
}
protected void btnSaveValue_Click(object sender, ImageClickEventArgs e)
{
lblResult.Text = "Value now is:" + valAlloc.getValue(); //DOESNT WORK??????!!!!!
}
}
public class valueAllocation
{
private int val;
public void setValue(int value)
{
val = value;
}
public string getValue()
{
return val;
}
}
最佳答案
这是因为您需要使用 ViewState
等来保存每个帖子中的值。
这是与 ASP.Net 页面生命周期相关的基本问题。
基本上,每次您请求页面时,都会在每个帖子上创建一个新的页面实例,并在响应返回客户端时销毁
如果你想在回发过程中保持状态,你需要手动保存ViewState
中的每个值
将整个类型存储在 ViewState 中
我认为这是你最好的选择
自定义类型
[Serializable]
public class valueAllocation
{
public int MyValue { get; set; }
}
隐藏代码
protected valueAllocation MyObject
{
get
{
if(this.ViewState["c"] != null)
return (valueAllocation)this.ViewState["c"];
return null;
}
set
{
this.ViewState["c"] = value;
}
public valueAllocation declaringValue()
{
if (this.MyObject == null)
this.MyObject = new valueAllocation { MyValue = 5 };
lblResult.Text="Value set here is:"+ this.MyObject.MyValue.ToString();
return this.MyObject;
}
protected void btnSaveValue_Click(object sender, ImageClickEventArgs e)
{
declaringValue()
lblResult.Text = "Value now is:" + declaringValue().MyValue.ToString();
}
关于c# - 事件处理程序中的属性值不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11558337/