My question is one line yet this is very confusing me.
Why i can not declare and initialize a session variable in partial class of a page it throws an error saying
Error 1 Invalid token ‘[‘ in class,
struct, or interface member
declaration E:\ASP.NET\Trial\statemanagement.aspx.cs 17 12 E:\ASP.NET\Trial\
below is the code i tried
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class statemanagement : System.Web.UI.Page
{
int count=0;
Session["FirstName"] = 0;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
count = int.Parse(Session["FirstName"].ToString());
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(count.ToString());
Session["FirstName"] =++count;
}
}
i dont get the error for count variable i dont know why?
Any help will be regarded thanks
That is not a declaration. It is an assignment. You can not place an assignment statement directly inside a class. You have to place it inside a method or property.
Refering to ASP.NET Session State Overview
If you like to initialize the session variables independently from the page you can use application event handlers such as
Application_StartandSession_Startwhich you can find in the global.asax file .