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>

4 Comments

  • I think its better to put this code in databound event

    Dim itm As New ListItem
    ' Define the item
    itm.Text = "-- Select --"
    itm.Value = "-1"
    ' itm.Selected = True ''' this line is not necessary so you can delete it
    ' 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 'this line is not necessary so you can delete it

  • Why not use AppendDataBoundItems?





    Raj Kaimal

  • @Jaime Cruz: You can use a required field validator for this. It has an initial value property that you would set to the value of your '-Select-' similar type statement. This requires the user to pick a value other than -Select-.

  • Thanks for the quick response Zack, made my day. :)

Comments have been disabled for this content.