Jonas Willander Jonas Willander - 25 days ago 7
ASP.NET (C#) Question

Incrementing variables in ASP.net 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();
myNumber++;
}

Answer

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