I'm working on a hit counter for my webpage in c# asp.net. I'm trying to use session state to display the string value of the hit counter from one web form and place it in another web form. It works but only after I navigate the links back and forth to test the increment, otherwise the first time I load the page the hit counter count doesn't display on the label. Any clue how i could fix this, I thought about using a cookie. But even if a first time visitor came to my page, my hit counter still wouldn't display correctly. I'm pretty desperate to solve this.
Here is the session state code I was trying with.
Form that is trying to display the label
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
namespace VideoWebsite
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string field1 = (string)(Session["field1"]);
Label1.Text = field1;
}
}
}
Form where I'm trying to get the session state value from
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn;
SqlCommand cmd;
using (conn)
{
//open the connection
conn.Open();
//send the query and store the results in a sqldatareader
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
//set the text of our label to the current # of hits
lblHits.Text = "Default Page Hits - " +
rdr["Hits"].ToString();
}
Session["field1"] = rdr["Hits"].ToString();
}
}
It will not display when first accessed because that session variable does not exist yet. You are only creating it in the second web form.
You should move that code that reads the information from the database to the session created event handler from global.asax.
Sorry I cannot post code, I'm typing from the Android app.
protected void Session_Start(object sender, EventArgs e)
{
// Your Hits read code goes here
}