Here I will explain how to count number of visitors to website in asp.net using C# and VB.NET or find or get number of visitors for a website in asp.net using C# and VB.NET.
Description
In previous articles I explained Asp.net Interview questions, Export Gridview data to PDF, Send values from one page to another page using QueryString, Joins in SQL Server, Highlight Gridview records based on search and many articles relating to Gridview, SQL, jQuery,asp.net, C#,VB.NET. Now I will explain how to count number of visitors to website in asp.net using C# and VB.NET.
To get number of visits for website we need to use methods in Global.asax file for that first add Global.asax file in your application
Open Visual Studio -à Create New Website-à Right click on Solution Explorer -à Select Add New Item-à Select Global Application Class file and click OK
Now open Global.asax file and write the code like as shown below
void Application_Start(object sender, EventArgs e) { // Code that runs on application startup Application["NoOfVisitors"] = 0; } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started Application.Lock(); Application["NoOfVisitors"] = (int)Application["NoOfVisitors"] + 1; Application.UnLock(); } |
In above code Application_Start event will raise only once when application starts and Session_Start event will raise for every postback operation if you want to know more about it check this What is Global.asax file and uses of it
Now open your aspx page and write the following code
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <table> <tr> <td> <b>No of Visits:</b> </td> <td> <asp:Label ID="lblCount" runat="server" ForeColor="Red" /> </td> </tr> </table> </form> </body> </html> |
Now in code behind add the following namespaces
C# Code
using System; |
After that add below code in code behind
protected void Page_Load(object sender, EventArgs e) { lblCount.Text = Application["NoOfVisitors"].ToString(); } |
VB.NET Code
Partial Class VbCode Inherits System.Web.UI.Page Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load lblCount.Text = Application("NoOfVisitors").ToString() End Sub End Class |
Demo
No comments:
Post a Comment