Reputation: 103
What is a simple way to count in C# how many times an asp net button has been clicked in the same page e.g page1.aspx? The counter should be valid per user and reset when I go to page2.aspx, then return back to page1.aspx. the counter should persist in case of reloading the same page.
the button is created dynamically in Page Init
Button x = new Button();
I cannot use javascript. thanks
Upvotes: 0
Views: 454
Reputation: 29036
The better way to use session, it enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. So that you can access the value even when you returning from page2.aspx
. the code for this will be
protected void button_Click(object sender, EventArgs e)
{
if(Session["ClickCount"]!=null)
Session["ClickCount"]=(int)Session["ClickCount"]++;
else
Session["ClickCount"]=0;
}
If you want to reset it when you leave the page means you can use:
if(Session["ClickCount"]!=null)
Session["ClickCount"]=0;
// Redirect to page
Upvotes: 0
Reputation: 3192
Create a class for maintain hit counters
public static class Counter
{
private static long hit;
public static void HitCounter()
{
hit++;
}
public static long GetCounter()
{
return hit;
}
}
Increment the value of counter at page load event
protected void Page_Load(object sender, EventArgs e)
{
Counter.HitCounter(); // call static function of static class Counter to increment the counter value
}
the time you redirect the user you can make count as null
Upvotes: 0