header
CodePanic! > C#.NET Tips > 今ここ

■選択されている項目を取得する

ListBoxで選択している項目を取得するには
SelectedIndexプロパティを参照します。

選択している項目を設定する場合も同様に
SelectedIndexプロパティに選択したい項目のインデックスを指定します。

下記はFormにListBoxを1つ、Buttonを1つ配置し
Buttonをクリックすると
選択している項目の文字列を表示するサンプルです。

        private void button1_Click(object sender, EventArgs e)
        {
            // 選択されている項目のインデックスを取得
            int index = listBox1.SelectedIndex;

            // 選択されていればインデックスに0以上の値が入ります
            if (index >= 0)
            {
                // 選択されている項目を表示(Itemsはobjectなのでキャストしています)
                string item = (string)listBox1.Items[index];
                MessageBox.Show(item);
            }

            // またはSelectedItemプロパティを参照します。
            // 何も選択されていなければnullが入っています
            MessageBox.Show((string)listBox1.SelectedItem);
        }

選択方法を変更する(単一選択、複数選択など)


ListBoxはデフォルトで単一選択ですが
SelectionModeプロパティの値を変更し
選択方法を変更することができます。

SelectionModeプロパティに設定できる値には次のものがあります。

    SelectionMode.One              一選択(デフォルトです)
    SelectionMode.MultiSimple       複数選択
    SelectionMode.MultiExtended     複数選択(CTRLやShiftキーでの選択も可能)
    SelectionMode.None              選択不可
    
複数選択の場合の
選択されている項目を取得する例は次のようになります。


        private void button1_Click(object sender, EventArgs e)
        {
            // 選択されているすべての項目の文字列を表示
            foreach (string item in listBox1.SelectedItems)
                Console.WriteLine(item);

            // 選択されているすべての項目のインデックスを表示
            foreach (int index in listBox1.SelectedIndices)
                Console.WriteLine(index);
        }





Copyright © 2008.07 - shougo suzaki