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:
And use
TheIndexinstead ofi.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.