如何:确定 List Web 服务器控件中的所选内容

更新:2007 年 11 月

本主题中的信息适用于这些 Web 服务器控件:ListBoxDropDownListCheckBoxListRadioButtonList

使用列表 Web 服务器控件时一个最常见的任务是确定用户已选择了哪一项或哪些项。具体过程取决于列表控件 (List Control) 允许单项选择还是多重选择。

在使用 DropDownList 控件、RadioButtonList 控件和单选 ListBox 控件时,请使用下面的过程。

确定单项选择列表控件 (List Control) 中的选定内容

  • 使用下列方法之一:

    • 若要获取选择项的索引值,请读取 SelectedIndex 属性的值。索引是从零开始的。如果未选择任何项,则该属性的值为 -1。

    • 若要获取选择项的内容,请获取该控件的 SelectedItem 属性。此属性返回一个 ListItem 类型的对象。通过获取该对象的 TextValue 属性可以获取选择项的内容。

      a5kfekd2.alert_security(zh-cn,VS.90).gif安全说明:

      Web 窗体页中的控件可能包含具有潜在危害的客户端脚本。默认情况下,Web 窗体页验证用户输入是否不包括脚本或 HTML 元素。有关更多信息,请参见如何:通过对字符串应用 HTML 编码在 Web 应用程序中防止脚本侵入

    下面的代码示例演示如何测试 RadioButtonList 控件中选择了哪一项。通过读取 SelectedIndex 属性的值,代码首先确定是否有选择内容,在用户选择一项之前该属性值设置为 -1。然后代码获取 SelectedItem 对象并显示该对象的 Text 属性。

    Protected Sub Button1_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Button1.Click
       ' Is anything selected? The index is -1 if nothing is selected.
       If RadioButtonList1.SelectedIndex > -1 Then
          Label1.Text="You chose: " & RadioButtonList1.SelectedItem.Text
       End If
    End Sub
    
    Protected void Button1_Click (object sender, System.EventArgs e)
    {
       // Is anything selected? The index is -1 if nothing is selected.
       if (RadioButtonList1.SelectedIndex > -1) {
          Label1.Text="You chose: " + 
              RadioButtonList1.SelectedItem.Text;
       }
    }
    

如果列表控件 (List Control) 支持多重选择,您就必须依次通过该控件,逐个检查选定项。

确定多重选择列表控件 (List Control) 中的选定内容

  • 依次通过控件的 Items 集合,分别测试每一项的 Selected 属性。

    下面的示例演示如何测试多选 ListBox 控件(名为 ListBox1)的所选内容。代码将在一个标签中显示选定项的列表。

    Protected Sub Button1_Click(ByVal sender As System.Object, _
           ByVal e As System.EventArgs) Handles Button1.Click
       Dim msg As String
       Dim li As ListItem
       msg = ""
       For Each li In ListBox1.Items
          If li.Selected = True Then
              msg = msg & "<br>" & li.Text & " selected."
          End If
       Next
       Label1.Text = msg
    End Sub
    
    Protected void Button1_Click(object sender, System.EventArgs e)
    {
       string msg = "" ;
       foreach(ListItem li in ListBox1.Items)
       {
          if(li.Selected == true)
             {
                msg += "<BR>" + li.Text + " is selected.";
             }
       }
       Label1.Text = msg;
    }
    

请参见

参考

CheckBox 和 CheckBoxList Web 服务器控件概述

DropDownList Web 服务器控件概述

ListBox Web 服务器控件概述

RadioButton 和 RadioButtonList Web 服务器控件概述