好吧,当我尝试执行代码时,我收到了NullReference异常。 我只是想在Viewstate [“contents”]中保存当前的学生实例。下次加载页面时,它会在para标签中显示前面的实例成员。
//代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
public student student1 = new student();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
para1.InnerText = "Last entered values were" + ((student)ViewState["contents"]).fname.ToString() + ((student)ViewState["contents"]).lname.ToString();
}
}
[Serializable]
public class student
{
public string fname { get; set; }
public string lname { get; set; }
}
protected void Button1_Click(object sender, EventArgs e)
{
student1.fname = TextBox1.Text;
student1.lname = TextBox2.Text;
}
protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["contents"] = student1;
}
}
答案 0 :(得分:1)
您必须覆盖预渲染。
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ViewState["contents"] = student1;
}
答案 1 :(得分:0)
您要在PreRender
事件后调用的Load
事件中设置值。因此,请尝试在Load
事件之前设置值。
Content page PreInit event.
Master page controls Init event.
Content controls Init event.
Master page Init event.
Content page Init event.
Content page Load event.
Master page Load event.
Master page controls Load event.
Content page controls Load event.
Content page PreRender event.
Master page PreRender event.
Master page controls PreRender event.
Content page controls PreRender event.
Master page controls Unload event.
Content page controls Unload event.
Master page Unload event.
Content page Unload event.
答案 2 :(得分:0)
public student student1 = new student();
protected void Page_Load(object sender, EventArgs e)
{
}
[Serializable]
public class student
{
public string fname { get; set; }
public string lname { get; set; }
}
protected void Button1_Click(object sender, EventArgs e)
{
student1.fname = TextBox1.Text;
student1.lname = TextBox2.Text;
ViewState["contents"] = student1;
}
protected void Page_PreRender(object sender, EventArgs e)
{
if (IsPostBack)
{
TextBox3.Text = "Last entered values were" + ((student)ViewState["contents"]).fname.ToString() + ((student)ViewState["contents"]).lname.ToString();
}
}
答案 3 :(得分:0)
试试这样。
在继续
之前,您需要检查Viewstate是否为nullprotected void Page_PreRender(object sender, EventArgs e)
{
ViewState["contents"] = student1;
}
protected void Button1_Click(object sender, EventArgs e)
{
student1.fname = TextBox1.Text;
student1.lname = TextBox2.Text;
ViewState["contents"] = student1;
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (ViewState["contents"] != null)
{
para1.InnerText = "Last entered values were" + ((student)ViewState["contents"]).fname.ToString() + ((student)ViewState["contents"]).lname.ToString();
}
}
}