I’ve been working in ASP.NET- just starting out, and I have a pretty simple question. I’ve got a button, and when you click it, it adds some simple text to a drop-down box. Here’s the code:
public partial class _Default : System.Web.UI.Page
{
private int buttonclickedtimes = 1;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
this.DropDownList1.Items.Add(new System.Web.UI.WebControls.ListItem("Clickin' mah buttonz " + buttonclickedtimes + " times!"));
buttonclickedtimes++;
}
}
But buttonclickedtimes always comes up as one. If I make the variable static, it works as intended. But the DropDownList is a member variable and it’s clearly properly stateful- as in, working as I expect. I don’t understand this behaviour- surely all member variables are either saved or not saved between requests? I’m running in debug mode in VS2010.
No, member variables are not saved between requests, if you want to save it, you need to put it in Viewstate.
The Control’s state is saved in Viewstate (if you have viewstate enabled) so that’s why it’s being saved between requests.
To save in Viewstate, add the following to a
Pre_Rendermethod:ViewState.Add("buttonClickTracker", buttonclickedtimes);And then access it:
buttonclickedTimes = Viewstate["buttonClickTracker"];