如何:设置列表 Web 服务器控件中的选定内容 (Visual Studio)

更新:2007 年 11 月

该主题中的信息适用于以下 Web 服务器控件:

通常,用户在列表 Web 服务器控件中选择项以指示他们的选择。但您也可能希望预先选择一些项,或者是在运行时(以编程方式)根据某些条件选择某些项。

在设计时设置列表 Web 服务器控件中的选定内容

  1. 在**“属性”窗口中,单击 Items 属性的省略号按钮 (VisualStudioEllipsesButton 屏幕快照) 打开“ListItem 集合编辑器”**对话框。

  2. 从**“成员”**列表中,选择要选定的成员,然后将它的 Selected 属性设置为 true。

  3. 如果该控件被设置为允许有多个选定内容,请对每个要选择的项重复步骤 2,然后单击**“确定”**关闭对话框。

以编程方式设置列表 Web 服务器控件中的单项选择

  • 执行下列操作之一

    • 将控件的 SelectedIndex 属性设置为要选择的项的索引值。索引是从零开始的。若要设置不选择任何项,请将 SelectedIndex 设置为 -1。

      dt1bzx2b.alert_note(zh-cn,VS.90).gif说明:

      如果将 DropDownList 控件的 SelectedIndex 属性设置为 -1,则该控件会将该值重置为 0(因为 DropDownList 控件始终会选择一个列表项)。

      ' Selects the third item
      ListBox1.SelectedIndex = 2
      
      // Selects the third item
      ListBox1.SelectedIndex = 2;
      
    • 设置列表中单个项的 Selected 属性。

      ' Selects the item whose text is Apples
      ListBox1.Items.FindByText("Apples")
      If Not li Is Nothing Then
         li.Selected = True
      End If
      
      // Selects the item whose text is Apples
      ListItem li = ListBox1.Items.FindByText("Apples");
      if(li != null)
      {
         li.Selected = true;
      }
      

以编程方式设置列表控件中的多重选择

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

    dt1bzx2b.alert_note(zh-cn,VS.90).gif说明:

    只有在控件的 SelectionMode 属性设置为 Multiple 时,才能选择多个项。

    下面的示例演示如何设置一个多重选择 ListBox 控件(名为 ListBox1)中的选定内容。该代码每隔一项选择一个。

    Protected Sub Button1_Click(ByVal sender As System.Object, _
             ByVal e As System.EventArgs) Handles Button1.Click
       Dim i As Integer
       Dim li As ListItem
       For Each li In ListBox1.Items
          i += 1
          If (i Mod 2 = 0) Then
             li.Selected = True
          End If
       Next
    End Sub
    
    Protected void Button1_Click(object sender, System.EventArgs e)
    {
       // Counter
       int i = 0;
       foreach(ListItem li in ListBox1.Items)
       {
          if( (i%2) == 0)
          {
             li.Selected = true; 
          }
          i += 1;
       }
    }
    

请参见

任务

如何:设置列表 Web 服务器控件中的选定内容 (Visual Studio)

如何:根据数据源来填充列表 Web 服务器控件 (Visual Studio)