Incrementing variables in ASP.net on button click

I am new to asp.net. I am creating a ASP.net website using VB.net. So here’s my problem

Dim myCounter as Integer = 0

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles Button1.Click

        myCounter =  myCounter + 1

        Label1.Text = myCounter.ToString()

end Sub

As expected I always get Label Text as 0 each time click the button. How to I create global variable and increment it.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Every time the page posts back, it is essentially starting over from scratch – anything initialized to 0, for example, will be zero again. This is because the server doesn’t know anything about the last time the page ran – all it knows is you clicked a button which submits a form to that page, so it creates another instance of the page and starts again.

If you need to persist a value across postbacks, the standard method is to use ViewState:

Public Property MyCounter() As Integer
    Get
        Dim val As Object = ViewState("MyCounter")
        Return If(val IsNot Nothing, CInt(val), 0)
    End Get
    Set(ByVal value As Integer)
        ViewState("MyCounter") = value
    End Set
End Property

It’s also possible to use Session, which will persist the value across all pages and requests for the life of the user’s session. For that to work, you can use the same sample above, replacing ViewState with Session.

Method 2

Put this code in your Button Click Event

int count=0;

count++;

ViewState["count"] = Convert.ToInt32(ViewState["count"]) + count;

Label1.Text = ViewState["count"].ToString();

Method 3

@Rex M’s suggestion for using Viewstate is good.

If the counter is not sensitive information or something you’re worried about someone tampering with., here’s an easier idea:

You can also use an <asp:HiddenField> and store the value there. Then it will persist between postbacks and you can increment it each time..

Method 4

Her’s another method that doesn’t use hidden field, viewstate, session or cache

Probably not something very ‘safe’ but probably saves you some time.

Assuming initial Label1.Text = 0

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles Button1.Click

        Label1.Text = (Integer.Parse(Label1.Text) + 1).ToString()

end Sub

Method 5

your page class gets recreated on each request… so myCounter won’t exist the next time.

you can either

  • make myCounter static (not a great idea)
  • put it in the Application, Session, or Cache collection

depends on what you’re trying to do

Method 6

You can use view count :—

Code on event of button_click..

ViewState["count"] = Convert.ToInt32(ViewState["count"])+1;
Label2.Text = "This button has been clicked " + ViewState["count"].ToString() + " times";

Method 7

   protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ViewState["Count"] = 0;
        }

    }

    protected void btnCount_Click(object sender, EventArgs e)
    {

        ViewState["Count"] = (int)(ViewState["Count"]) + 1;
        lblCount.Text = "Page Visited " +ViewState["Count"].ToString() +" times !";
        //Response.Write(ViewState["Count"].ToString());

    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x