HashTable – Binding to DropDownList/ListBox

This example shows how to load a HashTable manually, and then bind it to both a DropDownList and a Listbox. Although binding methods for both these controls are exactly the same, sometimes it helps to actually see it in action.

If you don’t know what a HashTable is, try thinking of it as a multi-dimensional array.

<html>
<head>
<meta name=”GENERATOR” Content=”ASP Express 2.1″>
<title>Untitled</title>
<script language=”VB” runat=”server”>
Sub Page_Load(Source as Object, E as EventArgs)

if not Page.IsPostBack then
Dim myHash As New Hashtable()
myHash.Add(“David”, 1)
myHash.Add(“Christopher”, 2)
myHash.Add(“Lisa”, 3)
myHash.Add(“Shannon”, 4)
myHash.Add(“James”, 5)

ddl.DataSource = myHash
lb1.DataSource = myHash
ddl.DataTextField = “Key”
lb1.DataTextField = “Key”
ddl.DataValueField = “Value”
lb1.DataValueField = “Value”
ddl.DataBind()
lb1.DataBind()
lb1.selectedIndex=0
end if
End Sub

Sub getDDL(Source as Object, E as EventArgs)
lblDDL.text=”DropDownList Text = ” & ddl.selectedItem.text & “<br>DropDownList Value = ” & ddl.selectedItem.value
End Sub

Sub getLB(Source as Object, E as EventArgs)
lblLB.text=”ListBox Text = ” & lb1.selectedItem.text & “<br>ListBoxValue = ” & lb1.selectedItem.value
End Sub
</script>
</head>
<body>
<Form id=”form1″ runat=”server”>
<div align=”center”>
<table width=”75%”> <tr>
<td align=”center” valign=”Top”>
<asp:DropDownList id=”ddl” runat=”server” /> <p>
<asp:Button id=”button1″ Text=”Get Selected” onclick=”getDDL” runat=”server” /><br>
<asp:Label ID=”lblDDL” runat=”server” />
</td>
<td align=”center” valign=”Top”>
<asp:ListBox id=”lb1″ runat=”server” /><p>
<asp:Button id=”button2″ Text=”Get Selected” onclick=”getLB” runat=”server” /><br>
<asp:Label ID=”lblLB” runat=”server” />
</td>
</tr>
</table></div>
</Form>
</body>

DropDownLists with Current Date and Month

This code sample shows how to use a for/next loop to populate two dropdownlists – one with 1-however many days in the month, for the date of the month, and one with the Months (value field=1-12). Also, it picks the current of each on Page_load

<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.1">
<title>DropDownLists with Date and Day</title>
<script language="vb" runat="server">
Sub Page_Load(sender As Object, e As EventArgs)
Dim x As Integer
Dim intDay, intMnth as integer
intDay=Day(now)
intMnth = Month(Now)
Dim MyDate as DateTime
MyDate=DateTime.Now
If Not IsPostBack Then
For x = 1 To 12
ddMonth.Items.Add(New ListItem(MonthName(x), x))
Next
‘ddDay.Items.Clear()
For x = 1 To MyDate.DaysInMonth(MyDate.Year, MyDate.Month)
ddDay.Items.Add(x)
Next
End If
ddDay.selectedIndex=intDay-1
ddMonth.selectedIndex=intMnth-1
end sub
</script>
</head>
<HTML>
<body>
<form id="Form1" method="post" runat="server">
<table>
<tr>
<td align="Left" valign="Top"><b>Day:</b></td><td align="Left" valign="Top"><b>Month:</b</td>
</tr>
<tr>
<td align="Left" valign="Top"><asp:DropDownList ID="ddDay" Runat="server"></asp:DropDownList></td>
<td align="Left" valign="Top"><asp:DropDownList ID="ddMonth" Runat="server" AutoPostBack="True"></asp:DropDownList> </td>
</tr>

</table>
</form>
</body>
</HTML>

Two DB Fields in DropDownList

Sometimes the need arises to include two database fields in a DropDownlist. However, since this is not possible, due to the fact that a DropDownList can only accept one db fieldname as a parameter for DataTextField, it becomes necessary to do this in a different way.

In this example, we take care of this by combining the fields in the SQL statement.

This code accesses the Employees table in the Northwind Database (SQL Server). To duplicate this on your machine, copy the code to a new page, and change the connection string to your specific database server.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<!– Created: 8/26/2002 9:27:56 AM –>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.1">
<title>Untitled</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
Dim sql as string = "Select FirstName + ‘ ‘ + LastName as fullname from Employees"
Dim conn as New SQLConnection(ConfigurationSettings.AppSettings("YourConnStringGoesHere"))
Dim Cmd as New SQLCommand(sql, conn)
conn.Open()
ddl.DataSource = Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
ddl.DataBind()
End Sub

Sub getitem(Source as Object, E as EventArgs)
label1.text=ddl.selecteditem.text
End Sub
</script>

</head>
<body>
<div align="center"><Form id="form1" runat="server">
<asp:DropDownList id="ddl" dataTextField="fullname" runat="server" /> <asp:Button id="button1" Text="Get Item" onclick="getitem" runat="server" /><P>
<asp:Label ID="label1" runat="server" />
</Form>
</div>

DropDownList – Values, Text and Querystrings

Let’s say you have a DropDownList which has records either from a database or some other data. You not only have a text value for the DropDownList which may relate to another datastore somewhere.

This sample creates a DropDownList with a numeric value and a text item for each entry in the list. Using that information, when selected, a label shows the value and the text, and an HTML link is created, using the value of the selected item in the DropDownList.

<html>
<head>
<meta name=”GENERATOR” Content=”ASP Express 2.0″>
<title>DropDownList – Values, Text and Querystrings</title>
<script language=”VB” runat=”server”>

Sub Page_Load(Source as Object, E as EventArgs)
Dim intID as Integer
intID= request.Querystring(“details”)

if intID>0 then
form1.visible=”false”
label1.visible=”false”
Select Case intID
Case 1
literal1.text=”John is 23 years old and lives in Cleveland and he’s unemployed”
Case 2
literal1.text=”Chris is 24 years old and lives in Dallas and he’s a programmer”
Case 3
literal1.text=”David is 28 years old and lives in Los Angeles and is a great guitar player”
Case 4
literal1.text=”Eric is 24 years old and lives in Oklahoma City and he works for the city”
End Select
Literal1.text=Literal1.text & “<br><a href=”"ddltest.aspx”">Start Over</a>”
End If

End Sub

Sub doit(Source as Object, E as EventArgs)
if ddl.selecteditem.text<>”" then
label1.text=”Value = ” & ddl.selecteditem.value & ” – Text = ” & ddl.selecteditem.text
Literal1.text=”<a href=”"ddltest.aspx?details=” & ddl.selecteditem.value & “”">Get Details for ” & ddl.selecteditem.text & “</a>”
End If
End Sub
</script>
</head>
<body>

<Form id=”Form1″ runat=”server”>
<asp:dropdownlist id=”ddl” runat=”server”>
<asp:listitem value=”1″ selected=”true”>John</asp:listitem>
<asp:listitem value=”2″>Chris</asp:listitem>
<asp:listitem value=”3″>David</asp:listitem>
<asp:listitem value=”4″>Eric</asp:listitem>
</asp:dropdownlist> <asp:Button id=”button1″ Text=”Get it” onclick=”doit” runat=”server” />
<br>
<asp:Label ID=”label1″ runat=”server” /><br>

</Form>
<asp:Literal ID=”Literal1″ runat=”server” />
</body>
</html>

Simple URL Re-director Using a DropDownList

Hey – you’ve all seen these HTML select lists before that, after you picked a web site from the list, you’d be redirected there. In the old days, this was commonly done with client-side Javascript.

This example shows a way this can be done using ASP.NET

<html>
<head>
<meta name=”GENERATOR” Content=”ASP Express 2.0″>
<title>DropDownList URL Picker</title>
<script language=”VB” runat=”server”>

Sub gothere(Source as Object, E as EventArgs)
response.Redirect(“http://” & ddl.selecteditem.text & “.com”)
End Sub

</script>
</head>
<body>

<Form id=”PutIDNameHere” runat=”server”><b>Choose URL: </b> <br>
<asp:dropdownlist id=”ddl” runat=”server”>
<asp:listitem selected=”true”>AspExpress</asp:listitem>
<asp:listitem>ASPWebhosting</asp:listitem>
<asp:listitem>123aspx</asp:listitem>
<asp:listitem>ASPFree</asp:listitem>
<asp:listitem>DotNetJunkies</asp:listitem>
<asp:listitem>ASPAlliance</asp:listitem>
</asp:dropdownlist>
<asp:Button id=”button1″ Text=”Go There” onclick=”gothere” runat=”server” />
</Form>

</body>
</html>

DataGrid – Changing the Column Size

Sometimes, it may become necessary to make a DataGrid column more narrow, or wider. This code sample, using the Northwind Database in SQL Server, uses the Employees database to show you just that.

To use this yourself, just copy the code to a new file, change the connection string/database info and you’ve got a running sample!

lt;%@ Import Namespace=”System.Data” %>
<%@ Import Namespace=”System.Data.SQLClient” %>
<html>
<head>
<meta name=”GENERATOR” Content=”ASP Express 2.0″>
<title>Change DataGrid Column Size</title>
<script language=”VB” runat=”server”>
Sub Page_Load(Source as Object, E as EventArgs)

if not Page.IsPostBack then
Dim strConn as string = “server=(local);uid=UserID;pwd=Password;database=Northwind”
Dim sql as string = “Select FirstName, LastName from Employees”
Dim conn as New SQLConnection(strConn)
Dim ds as DataSet=New DataSet()
Dim Cmd as New SQLDataAdapter(sql,conn)
Cmd.Fill(ds,”Employees”)
MyDataGrid.Datasource=ds.Tables(“Employees”).DefaultView
MyDataGrid.DataBind()

end if
End Sub
Sub changesize(Source as Object, E as EventArgs)
Dim intSize as integer
intSize=size.selecteditem.text
MyDataGrid.Columns(0).ItemStyle.Width=Unit.percentage(intSize)
End Sub

</script>
</head>
<body>
<form runat=”server” method=”post”>
<asp:Datagrid runat=”server”
Id=”MyDataGrid”
GridLines=”Both”
cellpadding=”0″
cellspacing=”0″
Headerstyle-BackColor=”#8080C0″
Headerstyle-Font-Name=”Arial”
Headerstyle-Font-Bold=”True”
Headerstyle-Font-Size=”8″
BackColor=”#8080FF”
Font-Name=”Arial”
Font-Bold=”True”
Font-Size=”8″
width=”100%”
BorderColor=”Black”
AutogenerateColumns=”False”>
<Columns>
<asp:BoundColumn DataField=”FirstName” SortExpression=”FirstName” HeaderText=”FirstName”></asp:BoundColumn>
<asp:BoundColumn DataField=”LastName” SortExpression=”LastName” HeaderText=”LastName”></asp:BoundColumn>
</Columns>
</asp:DataGrid>

<asp:dropdownlist id=”size” runat=”server”>
<asp:listitem selected=”true”>10</asp:listitem>
<asp:listitem>20</asp:listitem>
<asp:listitem>30</asp:listitem>
<asp:listitem>50</asp:listitem>
</asp:dropdownlist><b>% </b> <asp:Button id=”button1″ Text=”change size” onclick=”changesize” runat=”server” />
</form>
</body>
</html>

DataGrid – Changing Page Size (# of Rows) Programmatically

Sometimes, you may find the need to change the number of rows shown on a DataGrid programmatically. The number of rows is known as the page size. This code sample shows how to do this using the Northwind Database customers table.

Just copy the code to your new page, change the connection string to your SQL Server and you’re up and running!

<%@ Import Namespace=”System.Data” %>
<%@ Import Namespace=”System.Data.SQLClient” %>
<!– Created: 8/14/2002 12:02:04 PM –>
<html>
<head>
<meta name=”GENERATOR” Content=”ASP Express 2.0″>
<title>Change DataGrid Page Size</title>
<script language=”VB” runat=”server”>
Sub Page_Change(sender As Object, e As DataGridPageChangedEventArgs)
MyDataGrid.CurrentPageIndex = e.NewPageIndex
BindData
End Sub

Sub Page_Load(Source As Object, E As EventArgs)
If Not Page.IsPostBack Then
BindData()
End If
End Sub

Sub changepagesize(Source as Object, E as EventArgs)
dosize
End Sub

Sub dosize()
if pagesize.selecteditem.text <>”" then
MyDataGrid.pagesize=pagesize.selecteditem.text
End If
With MyDataGrid
Try
binddata
Catch
.currentpageindex=0
finally
binddata
End Try
end with

End Sub

Sub BindData()
Dim strConn as string = “(local);uid=userID;pwd=pwd;database=Northwind”
Dim sql as string = “Select CustomerID, CompanyName, ContactName, Phone from Customers”
Dim conn as New SQLConnection(strConn)
Dim ds as DataSet=New DataSet()
Dim Cmd as New SQLDataAdapter(sql,conn)
Cmd.Fill(ds,”Customers”)
MyDataGrid.Datasource=ds.Tables(“Customers”).DefaultView
MyDataGrid.DataBind()
End Sub
</script>
</head>
<body>
<div align=”center”><form runat=”server” method=”post”>
<asp:Datagrid runat=”server”
Id=”MyDataGrid”
GridLines=”Both”
cellpadding=”0″
cellspacing=”0″
Headerstyle-BackColor=”#8080C0″
Headerstyle-Font-Name=”Arial”
Headerstyle-Font-Bold=”True”
Headerstyle-Font-Size=”10″
BackColor=”#8080FF”
Font-Name=”Arial”
Font-Bold=”True”
Font-Size=”10″
BorderColor=”Black”
AllowPaging = “True”
PagerStyle-Mode = “NumericPages”
OnPageIndexChanged = “Page_Change”
AutogenerateColumns=”False”>
<Columns>
<asp:BoundColumn DataField=”CustomerID” SortExpression=”CustomerID” HeaderText=”CustomerID”></asp:BoundColumn>
<asp:BoundColumn DataField=”CompanyName” SortExpression=”CompanyName” HeaderText=”CompanyName”></asp:BoundColumn>
<asp:BoundColumn DataField=”ContactName” SortExpression=”ContactName” HeaderText=”ContactName”></asp:BoundColumn>
<asp:BoundColumn DataField=”Phone” SortExpression=”Phone” HeaderText=”Phone”></asp:BoundColumn>
</Columns>
</asp:DataGrid>
<table> <tr>
<td align=”center” valign=”Top”><b><i>Change Page Size:</i></b>
<asp:dropdownlist id=”pagesize” runat=”server” autopostback=”true” OnSelectedIndexChanged=”changepagesize”>
<asp:listitem selected=”true”></asp:listitem>
<asp:listitem>5</asp:listitem>
<asp:listitem>10</asp:listitem>
<asp:listitem>15</asp:listitem>
<asp:listitem>20</asp:listitem>
<asp:listitem>30</asp:listitem>
<asp:listitem>40</asp:listitem>
</asp:dropdownlist> <i>(number of rows shown in DataGrid)</i></td>
</tr>
</table>
</form></div>

</body>
</html>

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>

Alphabetized Filtering with a DataGrid

Sometimes, there’s a need (let’s say for an online phone book) to sort a database by the first letter of one of the database fields. For a phone book, this would normally be the last name field.

Here we have an example of doing just that. It’s hitting the Authors table of the Pubs database. For this specific example, it’s using SQL Server. All you’ll need to do is to copy the code to your page, name the file ‘alpha.aspx’, change the connection string to your db connection string and run it!

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.0">
<title>Alphabetized DataGrid Filtering</TITLE>
<Link REL=STYLESHEET HREF="/basicArial.css" TYPE="text/css">
<script language="VB" runat="server">
Dim strAlpha as string
Dim MySQL as string

Sub Page_Load(Source As Object, E As EventArgs)
strAlpha=request.Querystring("alpha")
If Not Page.IsPostBack Then
BindData()
End If
End Sub

Sub BindData()
strAlpha=request.Querystring("alpha")
if strAlpha="" then
MySQL="Select au_lname, au_Fname, Address, City, State from Authors order by au_lname"
else
MySQL="Select au_lname, au_Fname, Address, City, State from Authors where " & _
"au_lname Like ‘" & strAlpha & "%" & "’"
End If
Dim strConn as string = "server=yourserver;uid=userid;pwd=password;database=pubs"
Dim ds as DataSet=New DataSet()
Dim Cmd as New SQLDataAdapter(MySQL,strConn)
Cmd.Fill(ds,"authors")
MyDataGrid.Datasource=ds.Tables("authors").DefaultView
MyDataGrid.DataBind()

End Sub

Sub MyDataGrid_ItemDataBound(Source as Object, E as DataGridItemEventArgs)
If e.Item.ItemType = ListItemType.Footer then
Dim x as Integer
SqlHolder.Text = string.empty
for x=65 to 90
SQLHolder.text=SQLHolder.text & "<a href=""alpha.aspx?alpha=" & chr(x) & chr(34) & _
" class=""LinkClass"">" & chr(x) & "</a> | "
next
SQLHolder.text=SQLHolder.text & " | <a href=""alpha.aspx"">All Names</a>"
End If
End Sub

Sub Page_Change(sender As Object, e As DataGridPageChangedEventArgs)
MyDataGrid.CurrentPageIndex = e.NewPageIndex
BindData
End Sub

</script>
</head>
<body>

<div align="center"><b><font Size="5">Alphabetized DataGrid Filtering</font></b> </div>
<form runat="server" method="post">
<asp:Datagrid runat="server"
Id="MyDataGrid"
GridLines="Both"
cellpadding="0"
cellspacing="0"
Headerstyle-BackColor="#8080C0"
Headerstyle-Font-Name="Arial"
Headerstyle-Font-Bold="True"
Headerstyle-Font-Size="12"
BackColor="#8080FF"
Font-Name="Arial"
Font-Bold="True"
Font-Size="10"
AlternatingItemStyle-BackColor="#CFCFCF"
AlternatingItemStyle-Font-Name="Arial"
AlternatingItemStyle-Font-Bold="True"
AlternatingItemStyle-Font-Size="10"
BorderColor="Black"
AllowPaging = "True"
PageSize = "5"
PagerStyle-Mode = "NumericPages"
PagerStyle-BackColor="#F0d2F0"
PagerStyle-HorizontalAlign="Center"
PagerStyle-PageButtonCount = "5"
OnPageIndexChanged = "Page_Change"
AutogenerateColumns="False"
OnItemDataBound="MyDataGrid_ItemDataBound"
Width="100%">
<Columns>
<asp:BoundColumn DataField="au_lname" SortExpression="au_lname" HeaderText="Last Name">
</asp:BoundColumn>
<asp:BoundColumn DataField="au_fname" SortExpression="au_fname" HeaderText="First Name">
</asp:BoundColumn>
<asp:BoundColumn DataField="address" SortExpression="address" HeaderText="Address">
</asp:BoundColumn>
<asp:BoundColumn DataField="city" SortExpression="city" HeaderText="City">
</asp:BoundColumn>
</Columns>
</asp:DataGrid><div align="center"><hr>
<asp:Label id="SqlHolder" runat="server" Visible="true" /><hr>
</div>
</form>
</body>
</html>

Simple Header/Footer User Controls

User controls are one of the greatest things to come along in a long time. For those coming from Classic ASP, you can ‘sort of’ compart them to the old include files, except these are much better and much more powerful. They are separate files, using the ‘.ascx’ file extension.

In this example, two user controls are used – one for the header (testheader.ascx) of the page and one for the footer (testfooter.ascx).

Just copy each section into pages on your system, creating the same hierarchical setup of these three pages, in order to run this example on your system.

Here’s the code for the header (testheader.ascx):
<div align=”center”>
<font Size=”5″><b>Test Header</b> </font><br>
1212 Mockingbird Heights<br>
Chicago, Il 90503<hr>
</div>

Here’s the code for the footer (testfooter.ascx):

<div align=”center”><hr>
<font Size=”2″><i>Test Footer</i><br> Copyright 2002, All Rights Reserved</font>
</div>

Now – here’s the main page, where each user control is inserted:

<%@ Register TagPrefix=”xprs” tagname=”footer” src=”Testfooter.ascx” %>
<%@ Register TagPrefix=”xprs” tagname=”header” src=”testheader.ascx” %>
<html>
<head>
<meta name=”GENERATOR” Content=”ASP Express 2.0″>
<title>Heading of Page Goes here</title>
</head>
<body>
<xprs:header runat=”server”/>
<i><font Color=”#0000FF”>As you can see – the Header is on the top of this page.
Two lines accomplish this – the registration above and the instantiation of the control in the page itself.</font></i> <p>

This is my text for the page. This is my text for the page. This is my text for the page. This is my text for the page.
This is my text for the page. This is my text for the page. This is my text for the page. This is my text for the page.
This is my text for the page. This is my text for the page. This is my text for the page. This is my text for the page. <p>
<i><font Color=”#0000FF”>Now, below, you can also see the Footer for this page.
Again – two lines accomplish this, also.</font></i> <xprs:footer runat=”server”/>
</body>
</html>