Arraylist – Adding Items/Sorting/Binding

This code sample shows how to add items dynamically, to an arraylist, which is assigned to a Session, and then sort (ascending) the items once new items are added. Another button is there for sorting in descending order

The arraylist is bound, in this case, to a listbox, although a dropdownlist would work just the same.

<html>
<head>
<meta name=”GENERATOR” Content=”ASP Express 2.0″>
<title>ArrayList</title>
<script language=”VB” runat=”server”>
Dim colshoppingList as ArrayList
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
colshoppingList=New Arraylist
colshoppingList.add(“eggs”)
colshoppingList.add(“milk”)
colshoppingList.add(“bread”)
colshoppingList.add(“corn”)
lb1.datasource=colshoppingList
lb1.databind
Session(“colShop”)=colshoppingList
end if
End Sub

Sub doSort(Source as Object, E as EventArgs)
Session(“colShop”).sort
lb1.datasource=Session(“colShop”)
lb1.databind
End Sub

Sub DoDesc(Source as Object, E as EventArgs)
Session(“colShop”).sort
Session(“colShop”).reverse
lb1.datasource=Session(“colShop”)
lb1.databind
End Sub

Sub addit(Source as Object, E as EventArgs)
Dim strItem as string
strItem=text1.text
Session(“colShop”).add(strItem)
text1.text=”"
lb1.datasource=Session(“colShop”)
lb1.databind
End Sub
</script>
</head>
<body>

<Form id=”form1″ runat=”server”>
<asp:ListBox id=”LB1″ SelectionMode=”Single” runat=”server” /><br>

<asp:TextBox id=”text1″ runat=”server” /> <asp:Button id=”button2″ Text=”AddItem” onclick=”Addit” runat=”server” />
<p>
<asp:Button id=”button1″ Text=”Sort ASC” onclick=”doSort” runat=”server” /> <asp:Button id=”button3″ Text=”Sort DESC” onclick=”DoDesc” runat=”server” />
</Form>

</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>