我正在运行一个Sql查询,其中where子句在每次按钮点击时都会更改。
现在where子句包含列表的索引。当按钮单击发生时,会发生页面加载,这会导致索引值初始化。
int i=0;
protected void Button1_Click(object sender, EventArgs e)
{
string str = lst1.ElementAt<string>(i++);
qr = "Select BdId,First_Name,Last_Name,Age,Gender,Relationship_status,Birthday from [User] where BdId='" + str + "'";
da2 = new SqlDataAdapter(qr, con);
da2.Fill(ds2);
Label1.Text = Label1.Text + " " + i.ToString();
}
我怎样才能避免这种情况发生?我希望索引值是全局的,这样每次按钮点击都不会再次实例化。
由于
答案 0 :(得分:4)
每次有页面请求时,都会创建该页面类的 new 实例来处理该请求。因此,任何字段都会重新初始化。
您可以在ViewState中存储值以记住各种请求的值:
private int TheIndex
{
set { ViewState["TheIndex"] = value; }
get
{
if (ViewState["TheIndex"] == null)
return 0;
return (int)ViewState["TheIndex"];
}
}
并使用TheIndex
代替i
。
修改强>
另外,正如CodeInChaos所说,使用更具描述性的名称。如果其他人(或您自己在几个月内)需要维护此代码,这将有助于理解代码。
答案 1 :(得分:0)
您可以将变量存储在ASP.Net提供的Session
对象中。您也可以查看this教程。
if(Session["CurrentIndex"] != null) i = (int) Session["CurrentIndex"];
else Session["CurrentIndex"] = i;
希望这适合你。