ListBox.SelectedIndexChanged 事件

定義

SelectedIndex 屬性或 SelectedIndices 集合變更時發生。

public:
 event EventHandler ^ SelectedIndexChanged;
public event EventHandler SelectedIndexChanged;
public event EventHandler? SelectedIndexChanged;
member this.SelectedIndexChanged : EventHandler 
Public Custom Event SelectedIndexChanged As EventHandler 

事件類型

範例

下列程式碼範例示範如何使用 SelectedIndexChanged 事件來搜尋並選取不同 ListBox 控制項中的專案。 此範例會 SelectedIndexChanged 使用 事件來判斷 中 ListBox 選取的專案何時變更。 然後範例程式碼會使用 SelectedItem 屬性讀取專案的文字,並使用第一 ListBox 個 中傳回 SelectedItem 的文字,在不同的 ListBox 上呼叫 FindString 方法。 如果在另 ListBox 一個 中找到專案,則會選取專案。 此範例要求已將兩 ListBox 個名為 listBox1listBox2 的控制項新增至表單,而且這兩 ListBox 個控制項都包含相同的專案。 此範例也需要在範例中定義的事件處理方法連接到 SelectedIndexChanged 的事件 listBox1

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 );
   }
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);
}
Private Sub listBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles listBox1.SelectedIndexChanged
   ' Get the currently selected item in the ListBox.
   Dim curItem As String = listBox1.SelectedItem.ToString()

   ' Find the string in ListBox2.
   Dim index As Integer = listBox2.FindString(curItem)
   ' If the item was not found in ListBox 2 display a message box, otherwise select it in ListBox2.
   If index = -1 Then
      MessageBox.Show("Item is not available in ListBox2")
   Else
      listBox2.SetSelected(index, True)
   End If
End Sub

備註

您可以為此事件建立事件處理常式,以判斷 中選取的 ListBox 索引何時已變更。 當您需要根據 中的目前選取範圍 ListBox ,在其他控制項中顯示資訊時,這非常有用。 您可以使用這個事件的事件處理常式,在其他控制項中載入資訊。

SelectionMode如果 屬性設定為 SelectionMode.MultiSimpleSelectionMode.MultiExtended ,則集合的任何變更 SelectedIndices ,包括從選取範圍中移除專案,都會引發這個事件。

如需處理事件的詳細資訊,請參閱 處理和引發事件

適用於

另請參閱