请使用以下代码:
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;
using System.Collections.Generic;
namespace Test
{
public partial class _Default : System.Web.UI.Page
{
private List<Customer> CustomerList;
protected void Page_Load(object sender, EventArgs e)
{
// Quickly Illustrate Creation of a List of that contains information;
//CustomerList = (!this.IsPostBack) ? new List<Customer>() : new List<Customer>((Customer[])ViewState["Customers"]);
if (IsPostBack)
CustomerList = new List<Customer>((Customer[])ViewState["Customers"]);
else
CustomerList = new List<Customer>();
// Convert the List to Array of Customers and Save To View State
// Rather than Handling Serialization Manually
//ViewState.Add("Customers", CustomerList.ToArray());
// While Reading the View State Information - Of course
// use correct checks to see the item is Not Null and All that... and then do:
//Customer[] newArray = (Customer[])ViewState["Customers"];
//List<Customer> newList = new List<Customer>(newArray);
//for (int i = 0; i < CustomerList.Count; i++)
// Response.Write(CustomerList[i].CustomerName + "\r\n");
}
protected void Page_Unload(object sender, EventArgs e)
{
for (int i = 0; i < CustomerList.Count; i++)
Response.Write(CustomerList[i].CustomerName + "\r\n");
ViewState.Add("Customers", CustomerList.ToArray());
}
protected void Button1_Click(object sender, EventArgs e)
{
Customer SingleCustomer = new Customer();
SingleCustomer.CustomerName = TextBox1.Text;
CustomerList.Add(SingleCustomer);
ViewState.Add("Customers", CustomerList.ToArray());
}
}
}
Run Code Online (Sandbox Code Playgroud)
它不起作用.每次我单击Add按钮并重新加载页面时,我会得到一个Null的NullReferenceException,CustomerList = new List<Customer>((Customer[])ViewState["Customers"]);因为它在ViewState中不存在.这是为什么?
页面卸载设置ViewState变量为时已晚
来自http://msdn.microsoft.com/en-us/library/ms178472.aspx:
在页面完全呈现,发送到客户端并准备好被丢弃之后引发Unload事件.此时,将卸载响应和请求等页面属性并执行清理.
ViewState本身作为页面中的隐藏字段发送 - 因此,如果您已将页面发送到客户端,则以后无法添加到ViewState.
尝试使用LoadComplete或PreRender事件?