WebForms ArrayList 学习笔记
什么是ArrayList?
ArrayList 是一个集合类,它可以存储任意类型的对象。与数组不同,它可以动态扩展和收缩大小,在需要添加或删除元素时非常方便。
如何使用ArrayList?
首先,我们需要在页面中声明一个 ArrayList 对象:
c#Copy CodeArrayList myArrayList = new ArrayList();
接下来,我们可以使用 Add 方法将元素添加到 ArrayList 中:
c#Copy CodemyArrayList.Add("apple");
myArrayList.Add(123);
myArrayList.Add(true);
我们还可以使用 Count 属性获取 ArrayList 中元素的数量:
c#Copy Codeint count = myArrayList.Count;
如果要访问特定的元素,可以使用索引:
c#Copy Codeobject item = myArrayList[0];
实例
以下是一个简单的示例,演示如何将用户在文本框中输入的数据添加到 ArrayList 中并显示在页面上:
htmlCopy Code<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
ArrayList myArrayList = (ArrayList)ViewState["MyArrayList"] ?? new ArrayList();
myArrayList.Add(TextBox1.Text);
ViewState["MyArrayList"] = myArrayList;
ListBox1.DataSource = myArrayList;
ListBox1.DataBind();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ArrayList Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Add" OnClick="Button1_Click" />
<br />
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
</div>
</form>
</body>
</html>
在这个示例中,用户在文本框中输入数据后,单击“Add”按钮将数据添加到 ArrayList 中,并将 ArrayList 绑定到 ListBox 上以显示所有元素。