DropDownList是用于创建HTML Select组件的Web服务器控件。它允许无涯教程从下拉列表中选择一个选项。它可以包含任意数量的项目
ASP.NET提供了一个标记来为Web应用程序创建DropDownList。以下是DropDownList标签的语法。
<asp:DropDownList id="DropDownList1" runat="server" DataSource="<% databindingexpression %>" DataTextField="DataSourceField" DataValueField="DataSourceField" AutoPostBack="True|False" OnSelectedIndexChanged="OnSelectedIndexChangedMethod"> <asp:ListItem value="value" selected="True|False"> Text </asp:ListItem> </asp:DropDownList>
无涯教程正在使用Visual Studio 2017创建DropDownList。此示例包括以下步骤。
通过指定新窗体的名称添加新窗体。
最初,它是一个空表单。现在,将通过从工具箱中拖动来添加一个新的DropDownList。
拖动后,Web表单如下所示。
现在,为了向列表中添加项目,Visual Studio提供了Items属性,可以在其中添加项目。属性窗口如下所示。
点击项目(Collection),将弹出一个新窗口,如下所示。最初,它没有任何项目。提供添加按钮将新项目添加到列表。
通过向Text和Value属性提供值,将项添加到DropDownList。
已经向其中添加了更多项目,现在,它看起来如下所示。
单击确定后,
DropDownListExample.aspx
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DropDownListExample._Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <p>Select a City of Your Choice</p> <div> <asp:DropDownList ID="DropDownList1" runat="server" > <asp:ListItem Value="">Please Select</asp:ListItem> <asp:ListItem>New Delhi </asp:ListItem> <asp:ListItem>Greater Noida</asp:ListItem> <asp:ListItem>NewYork</asp:ListItem> <asp:ListItem>Paris</asp:ListItem> <asp:ListItem>London</asp:ListItem> </asp:DropDownList> </div> <br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" /> <br /> <br /> <asp:Label ID="Label1" runat="server" EnableViewState="False"></asp:Label> </form> </body> </html>
//DropDownListExample.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace DropDownListExample { public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { if (DropDownList1.SelectedValue == "") { Label1.Text = "Please Select a City"; } else Label1.Text = "Your Choice is: " + DropDownList1.SelectedValue; } } }
输出:
在服务器端,获取选定的城市并显示给用户。
链接:https://www.learnfk.comhttps://www.learnfk.com/asp.net_mvc/asp-net-dropdownlist.html
来源:LearnFk无涯教程网
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)