讓使用者能夠從單一選取式的下拉式清單中選取。下拉式清單可以含有任何數目的項目。
<asp:DropDownListid="DropDownList1" runat="server" DataSource="<% databindingexpression %>" DataTextField="DataSourceField" DataValueField="DataSourceField" AutoPostBack="True|False" OnSelectedIndexChanged="OnSelectedIndexChangedMethod"> <asp:ListItemvalue="value" selected="True|False"> Text </asp:ListItem></asp:DropDownList>
備註
使用 DropDownList 控制項來建立單一選取式的下拉式清單控制項。您可以設定 BorderColor、BorderStyle 和 BorderWidth 屬性,來控制 DropDownList 控制項的外觀。
若要指定要出現在 DropDownList 控制項中的項目 (Item),請將每一項目 (Entry) 的 ListItem 項目 (Element) 置於 DropDownList 控制項的開始和結束標記之間。
DropDownList 控制項也支援資料繫結。若要將控制項繫結至資料來源,請先建立含有要在控制項中顯示之項目的資料來源,例如 System.Collections.ArrayList。然後,使用 Control.DataBind 方法將資料來源繫結至 DropDownList 控制項。使用 DataTextField 和 DataValueField 屬性來指定資料來源中哪個欄位要分別繫結至控制項中每一清單項目的 Text 和 Value 屬性。DropDownList 控制項不會顯示來自資料來源的資訊。
使用 SelectedIndex 屬性,以程式設計的方式來判斷使用者在 DropDownList 控制項中所選取項目的索引。然後,這個索引就可以用來從控制項的 Items 集合擷取選取的項目。
如需 DropDownList Web 伺服器控制項之屬性和事件的詳細資訊,請參閱 DropDownList 文件。
範例
下列範例是示範如何使用 DropDownList 控制項。
<%@ Page Language="VB" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
Sub Button_Click(sender As Object, e As EventArgs)
Label1.Text = "You selected " & _
DropDownList1.SelectedItem.Text & "."
End Sub 'Button_Click
</script>
</head>
<body>
<form runat="server">
<h3>DropDownList Example</h3>
Select an item from the list and click the submit button.
<p>
<asp:DropDownList id="DropDownList1"
runat="server">
<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem>Item 4</asp:ListItem>
</asp:DropDownList>
<br><br>
<asp:Button id="Button1"
Text="Submit"
OnClick="Button_Click"
runat="server"/>
<br><br>
<asp:Label id="Label1"
runat="server"/>
</form>
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
void Button_Click(Object sender, EventArgs e)
{
Label1.Text = "You selected: " +
dropdownlist1.SelectedItem.Text + ".";
}
</script>
</head>
<body>
<form runat="server">
<h3>DropDownList Example</h3>
Select an item from the list and click the submit button.
<p>
<asp:DropDownList id="dropdownlist1" runat="server">
<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem>Item 4</asp:ListItem>
</asp:DropDownList>
<br><br>
<asp:Button id="Button1"
Text="Submit"
OnClick="Button_Click"
runat="server"/>
<br><br>
<asp:Label id="Label1" runat="server"/>
</form>
</body>
</html>