英語で読む

次の方法で共有


ListBox.SelectedItem プロパティ

定義

ListBox 内で現在選択されている項目を取得または設定します。

[System.ComponentModel.Bindable(true)]
[System.ComponentModel.Browsable(false)]
public object SelectedItem { get; set; }
[System.ComponentModel.Bindable(true)]
[System.ComponentModel.Browsable(false)]
public object? SelectedItem { get; set; }

プロパティ値

コントロール内で現在選択されている項目を表すオブジェクト。

属性

次のコード例では、 イベントを使用して、別ListBoxSelectedIndexChangedコントロール内の項目を検索して選択する方法を示します。 この例では、 イベントを SelectedIndexChanged 使用して、 で選択した項目がいつ変更されたかを ListBox 判断します。 次に、コード例では、 プロパティを使用して項目のテキストをSelectedItem読み取り、最初ListBoxの で によってSelectedItem返されるテキストを使用して、別ListBoxの で メソッドを呼び出FindStringします。 もう一方 ListBoxの で項目が見つかった場合は、項目が選択されます。 この例では、 と listBox2という名前listBox1の 2 つのListBoxコントロールがフォームに追加され、両方ListBoxのコントロールに同じ項目が含まれている必要があります。 この例では、例で定義されているイベント処理メソッドが のイベントlistBox1SelectedIndexChanged接続されている必要もあります。

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決定できます。 の ListBox プロパティが SelectionMode または SelectionMode.MultiExtended (複数選択ListBoxを示す) にSelectionMode.MultiSimple設定されていて、リスト内で複数の項目が選択されている場合、このプロパティは選択した項目を返すことができます。

複数選択 ListBoxされている内のすべての選択項目を含むコレクションを取得するには、 プロパティを SelectedItems 使用します。 で ListBox現在選択されている項目のインデックス位置を取得する場合は、 プロパティを SelectedIndex 使用します。 さらに、 プロパティを SelectedIndices 使用すると、複数選択 ListBoxの 内で選択したすべてのインデックスを取得できます。

適用対象

製品 バージョン
.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