使用英语阅读

通过


ListBox.SelectedIndexChanged 事件

定义

SelectedIndex 属性或 SelectedIndices 集合更改后发生。

public event EventHandler SelectedIndexChanged;
public event EventHandler? SelectedIndexChanged;

事件类型

示例

下面的代码示例演示如何使用 SelectedIndexChanged 事件在不同控件中 ListBox 搜索和选择项。 该示例使用 SelectedIndexChanged 事件来确定 中 ListBox 所选项的更改时间。 然后,示例代码使用 SelectedItem 属性读取项的文本,并使用第一ListBox个 中返回SelectedItem的文本在不同的 ListBox 上调用 FindString 方法。 如果在另 ListBox一个 中找到某个项,则选择该项。 此示例要求已将两 ListBox 个名为 listBox1listBox2的控件添加到窗体中,并且这两 ListBox 个控件包含相同的项。 该示例还要求示例中定义的事件处理方法连接到 SelectedIndexChangedlistBox1事件。

private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
   // Get the currently selected item in the ListBox.
   string curItem = listBox1.SelectedItem.ToString();

   // Find the string in ListBox2.
   int index = listBox2.FindString(curItem);
   // If the item was not found in ListBox 2 display a message box, otherwise select it in ListBox2.
   if(index == -1)
      MessageBox.Show("Item is not available in ListBox2");
   else
      listBox2.SetSelected(index,true);
}

注解

可以为此事件创建事件处理程序,以确定何时更改了 中的 ListBox 选定索引。 如果需要根据 中的当前选择在其他控件中显示信息, ListBox这非常有用。 可以使用此事件的事件处理程序在其他控件中加载信息。

如果 属性 SelectionMode 设置为 SelectionMode.MultiSimpleSelectionMode.MultiExtended,则对 SelectedIndices 集合所做的任何更改(包括从所选内容中删除项)都将引发此事件。

有关处理事件的详细信息,请参阅 处理和引发事件

适用于

产品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

另请参阅