Filling an ArrayList from a Database Table

Some ASP.Net server controls do not have a sort property, among other things that might be needed. Therefore, it becomes necessary to use an ArrayList, or the like, so that you can work with the ArrayList itself and then bind it to the server control, like a DropDownList, which is used in this sample.

This is a very simple example of reading through the records of a table, using SQL Server and the Northwind Database (Categories table), adding the items to the ArrayList, and then, binding the ArrayList to the DropDownList

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.1">
	<title>Untitled</title>
<script language="VB" runat="server">
Dim MyArrayList as ArrayList
Dim sItem as String
Sub Page_Load(Source as Object, E as EventArgs)
MyArrayList=New Arraylist
if not Page.IsPostBack then
Dim strConn as string = "server=YourServer;uid=UID;pwd=PWD;database=NorthWind"
	Dim MySQL as string = "Select CategoryName from Categories"
	Dim MyConn as New SQLConnection(strConn)
	Dim objDR as SQLDataReader
	Dim Cmd as New SQLCommand(MySQL, MyConn)
	MyConn.Open()
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	While objDR.Read()
		MyArrayList.add(objDR("CategoryName"))
	End While
end if
ddl1.datasource=MyArrayList
ddl1.databind
End Sub
</script>
</head>
<body>

<Form id="form1" runat="server">
<asp:DropDownList id="ddl1" 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>