C# 菜鸟的赋值问题。
<body>
<form id= "form1 " runat= "server ">
<div>
<asp:Button ID= "Button1 " runat= "server " Text= "Button " OnClick= "Button1_Click " />
</div>
</form>
</body>
public partial class ceshi : System.Web.UI.Page
{
private string str;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.str = "1000 ";
}
Response.Write( "初始化输出: " + this.str + " <br> ");
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write( "点击按钮后输出: " + this.str + " <br> ");
}
}
想问问,页面在LOAD 是,已经赋值给 private string str;但为什么在按钮事件中他的值是空呢?
------解决方案--------------------string str{
get {
object o = ViewState[ "str "];
if (o == null) {
return String.Empty;
}
return (string)o;
}
set {
ViewState[ "SortField "] = value;
}
}
一般 用viewstate
或是javascript放在隐藏域里,提交后Request.From[] 得到
或是去掉
if (!this.IsPostBack)
{
}
------解决方案--------------------private string str;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.str = "1000 ";
}
Response.Write( "初始化输出: " + this.str + " <br> ");
}
当回发时,你相当于又重新声明了一个变量,但第二次你不能执行
if (!this.IsPostBack)
{
this.str = "1000 ";
}
所以得到空值
------解决方案--------------------在web 页面级别的全局变量 最好用
ViewState[ "str "]
------解决方案--------------------点按钮已经是第二次访问了也就是说已经是回传页了,this.str = "1000 ";当然执行不到