public virtual ListItem SelectedItem { get { int selectedIndex = this.SelectedIndex; if (selectedIndex >= 0) { return this.Items[selectedIndex]; } return null; } } public virtual string SelectedValue { get { int selectedIndex = this.SelectedIndex; if (selectedIndex >= 0) { return this.Items[selectedIndex].Value; } return string.Empty; } }
在沒有標明任何項的情況下,SelectedValue預設值是string.Empty,而SelectedItem預設值是null(也就是說通過SelectedItem.Value可能發生異常)
1. selectedIndex——指的是dropdownlist中選項的索引,為int,從0開始,可讀可寫
2. selectedItem——指的是選中的dropdownlist中選項,為ListItem,隻讀不寫
3. selectedValue——指的是選中的dropdownlist中選項的值,為string, 隻讀不寫
4. selectedItem.Text——指的是選中的dropdownlist中選項的文本内容,與selectedItems的值一樣為string,可讀可寫
5. selectedItem.value——指的是選中的dropdownlist中選項的值,與selectedValue的值一樣,為string,可讀可寫
光看文字可能不太了解,我也是通過程式來加深了解的,下面舉個例子:
前台代碼:
代碼
1 view plaincopy to clipboardprint?
2 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="dropdown.aspx.cs" Inherits="dropdown" %>
3
4 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
5
6 <html xmlns="http://www.w3.org/1999/xhtml" >
7 <head runat="server">
8 <title>無标題頁</title>
9 </head>
10 <body>
11 <form id="form1" runat="server">
12 <div>
13 <asp:DropDownList ID="DropDownList1" runat="server">
14 <asp:ListItem Value="1">北京</asp:ListItem>
15 <asp:ListItem Value="2">上海</asp:ListItem>
16 <asp:ListItem Value="3">廣州</asp:ListItem>
17 </asp:DropDownList>
18 <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="check" /><br />
19 <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
20 <br />
21 <asp:Label ID="Label2" runat="server" Text=""></asp:Label>
22 <br />
23 <asp:Label ID="Label3" runat="server" Text=""></asp:Label><br />
24 <asp:Label ID="Label4" runat="server" Text=""></asp:Label>
25 <br />
26 <asp:Label ID="Label5" runat="server" Text=""></asp:Label>
27
28 </div>
29 </form>
30 </body>
31 </html>
背景代碼:
代碼
1 using System;
2 using System.Data;
3 using System.Configuration;
4 using System.Collections;
5 using System.Web;
6 using System.Web.Security;
7 using System.Web.UI;
8 using System.Web.UI.WebControls;
9 using System.Web.UI.WebControls.WebParts;
10 using System.Web.UI.HtmlControls;
11
12 public partial class dropdown : System.Web.UI.Page
13 {
14 protected void Page_Load(object sender, EventArgs e)
15 {
16
17 }
18 protected void Button1_Click(object sender, EventArgs e)
19 {
20 Label1.Text = "selectedIndex=" + DropDownList1.SelectedIndex;
21 Label2.Text = "selectedItem=" + DropDownList1.SelectedItem;
22 Label3.Text = "selectedValue=" + DropDownList1.SelectedValue;
23 Label4.Text = "selectedItem.text=" + DropDownList1.SelectedItem.Text;
24 Label5.Text = "selectedItem.value=" + DropDownList1.SelectedItem.Value;
25 }
26 }