protected void Button1_Click(object sender, EventArgs e) { Test test = ViewState["VIEW_TEST"] as Test; if (test == null) { test = new Test(); } test[-1] = TextBox1.Text;
[SerializableAttribute] class Test : DataTable { public Test() { DataColumn col = new DataColumn(); col.DataType = typeof(string); col.ColumnName = "name"; this.Columns.Add(col); }
public object this[int index] { get { if (index >= Rows.Count) { return null; } return Rows[index]["name"]; } set { DataRow row = NewRow(); row["name"] = value; Rows.Add(row); } } }那麼再把這個類放入VIEwState的話就會報錯:此頁的狀態信息無效,可能已損壞,主要是因為它的父類DataTable是不可序列化的,我們就需要把這個類改造成如下形式:
[SerializableAttribute] class Test : DataTable, System.Runtime.Serialization.ISerializable
public Test() { DataColumn col = new DataColumn(); col.DataType = typeof(string); col.ColumnName = "name"; this.Columns.Add(col); }
public object this[int index] { get { if (index >= Rows.Count) { return null; } return Rows[index]["name"]; } set { DataRow row = NewRow(); row["name"] = value; Rows.Add(row); } }
public Test(SerializationInfo info, StreamingContext context) { DataColumn col = new DataColumn(); col.DataType = typeof(string); col.ColumnName = "name"; this.Columns.Add(col);
ArrayList list = info.GetValue("list", typeof(ArrayList)) as ArrayList; foreach (string value in list) { DataRow row = NewRow(); row["name"] = value; Rows.Add(row); } }
public void GetObjectData(SerializationInfo info, StreamingContext context) { ArrayList list = new ArrayList(); foreach (DataRow row in this.Rows) { list.Add(row["name"]); } info.AddValue("list", list); }