Jonas Willander Jonas Willander - 1 year ago 74
ASP.NET (C#) Question

Incrementing variables in on every button click

I want to increment date in every click ASP.NET.
But Every time the page posts back, it is essentially starting over from scratch - anything initialized to 0.
I need to persist a value across postbacks but I don't how to do that. I would appreciate for any help.
Here is what I'am trying to do:

int myNumber = 0;
protected void Button1_Click1(object sender, EventArgs e)
lblDate.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(myNumber).ToShortDateString();

Answer Source

I have updated your code below by using ViewState to handle this. Other easiest option would be storing the same in Session, Cache or Cookie.

While storing a value in ViewState, it will create a hidden field in the page and store the value to maintain it across the postback.

public int Count
    get { return ViewState["Count"] != null ? (int)ViewState["Count"] : 0; }
    set { ViewState["Count"] = value; }

protected void Button1_Click1(object sender, EventArgs e)
  lblDate.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(Count).ToShortDateString();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download