共用方式為


ListBox.SelectedIndexChanged 事件

定義

當財產或SelectedIndices收藏發生變化時SelectedIndex

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屬性讀取該項目的文字,並FindString利用第一個 ListBox中回傳的SelectedItem文字呼叫該ListBox方法。 如果在另一個 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 集合的變更,包括從選取中移除項目,都會觸發此事件。

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

適用於

另請參閱