0
看看下面的代码:如何在ViewState中保存数组并在页面卸载后能够检索它?
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());
}
}
}
它不工作。每次点击添加按钮并重新加载页面时,我都会得到一个NullReferenceException,因为它不在ViewState中。“CustomerList = new List<Customer>((Customer[])ViewState["Customers"]);
”这是为什么?