简体   繁体   中英

How to avoid instantiation of variable after button click?

I am running a Sql query whose where clause changes everytime when button click occurs.

Now the where clause consists of an index to the list. When the button click happens ,page load occurs which causes the index value intialisation.

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();
}

How can I avoid this happening? I want index value to be global so that it doesn't instantiate again every time button click occurs.

Thanks

Every time there is a request for your page, a new instance of that page-class is created to handle that request. So any fields are re-initialized.

You can store a value in ViewState to remember a value over various requests:

private int TheIndex
{
   set { ViewState["TheIndex"] = value; }
   get 
   {
      if (ViewState["TheIndex"] == null)
         return 0;
      return (int)ViewState["TheIndex"];
   }
}

And use TheIndex instead of i .

EDIT
Plus, as CodeInChaos notes, use a more descriptive name. That will help in understanding the code if someone else (or you yourself in a few months) needs to maintain this code.

You can store the variable in Session object provided by ASP.Net. You can check this tutorial also.

if(Session["CurrentIndex"] != null) i = (int) Session["CurrentIndex"];
else Session["CurrentIndex"] = i;

Hope this works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM