//源页中用来保存用户名到会话状态并重定向到目标页的代码如下:protected void SubmitButton_Click(object sender, EventArgs e){ this.Session["UserName"] = this.UserNameTextBox.Text; this.Response.Redirect("DestinationPage.aspx");} //目标页中获取保存在会话状态中的用户名的代码如下:
protected void Page_Load(object sender, EventArgs e){ string UserName = this.Session["UserName"].ToString(); this.Response.Write(UserName);}
我使用这种传递方式怎么总是出错啊?如下:
未将对象引用设置到对象的实例。
说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。
protected void Page_Load(object sender, EventArgs e){ string UserName = this.Session["UserName"].ToString(); this.Response.Write(UserName);}
我使用这种传递方式怎么总是出错啊?如下:
未将对象引用设置到对象的实例。
说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。
if(this.Session["UserName"]!=null)
{
string UserName = this.Session["UserName"].ToString(); this.Response.Write(UserName);}
else
{this.Response.Write("session会话失效");
}
但按你的这种写法Session["UserName"]应不会为空的可以这样写string UserName=Convert.ToString(this.Session["UserName"]);
这样就不会有你那种错误了