Display ‘–Select–’ in an ASP.NET DropDownList
A purchaser of my book writes:
“I would like a drop down list to display the text: "-Select-" initially instead of the first value of the data it is bound to.”
Here you go…
<%@ Page Language="VB" %>
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs)
If Not IsPostBack Then
' Create some data
Dim q = From tz As TimeZoneInfo _
In System.TimeZoneInfo.GetSystemTimeZones() _
Select tz.DisplayName, tz.Id, tz.BaseUtcOffset _
Order By BaseUtcOffset
' Tell the ddl to use the data
DropDownList1.DataSource = q
' Tell the ddl what data to use where
DropDownList1.DataTextField = "DisplayName"
DropDownList1.DataValueField = "Id"
' Tell the ddl to absorb this data
DropDownList1.DataBind()
' Create a new item
Dim itm As New ListItem
' Define the item
itm.Text = "-- Select --"
itm.Value = "-1"
itm.Selected = True
' Jam the item into the ddl as the first one
DropDownList1.Items.Insert(0, itm)
' Tell the ddl to select the first item
DropDownList1.SelectedIndex = 0
End If
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
</div>
</form>
</body>
</html>