将对象保存在 ASP.net 中的 ArrayList 中
Save objects in an ArrayList in ASP.net
ArrayList aList = new ArrayList();
protected void Button1_Click(object sender, EventArgs e)
{
aList.Add(DropDownList1.SelectedValue);
ListBox1.DataSource = aList;
ListBox1.DataBind();
}
以上代码仅将最后插入的数据绑定到数组列表中。
不显示列表中之前添加的数据。
如何让列表中的项目一直显示?
每次您 post 向网页发出请求时都会重新创建该列表,因此它不是永久性的。
您有几个选项可以永久保存:
例如使用Session
:
protected void Button1_Click(object sender, EventArgs e)
{
ArrayList aList = (ArrayList)this.Session["someParameter"];
if (aList == null)
{
this.Session["someParameter"] = aList = new ArrayList();
}
aList.Add(DropDownList1.SelectedValue);
ListBox1.DataSource = aList;
ListBox1.DataBind();
}
此外,请不要再使用 ArrayList
,而是通用的 List<T>
。
ArrayList aList = new ArrayList();
protected void Button1_Click(object sender, EventArgs e)
{
aList.Add(DropDownList1.SelectedValue);
ListBox1.DataSource = aList;
ListBox1.DataBind();
}
以上代码仅将最后插入的数据绑定到数组列表中。
不显示列表中之前添加的数据。
如何让列表中的项目一直显示?
每次您 post 向网页发出请求时都会重新创建该列表,因此它不是永久性的。
您有几个选项可以永久保存:
例如使用Session
:
protected void Button1_Click(object sender, EventArgs e)
{
ArrayList aList = (ArrayList)this.Session["someParameter"];
if (aList == null)
{
this.Session["someParameter"] = aList = new ArrayList();
}
aList.Add(DropDownList1.SelectedValue);
ListBox1.DataSource = aList;
ListBox1.DataBind();
}
此外,请不要再使用 ArrayList
,而是通用的 List<T>
。