HIRO's.NET

VB.NET, C#, PowerShell Tipsサイト

 VB.NET, C#, PowerShellを使用しているエンジニアのためのサイト。

 基本的な使用方法から開発で役立つTipsまで幅広く取り扱っています。

HIRO's.NET RSSHIRO's.NET RSS


C# 2005の開発でお困りのことはありませんか?
そんな悩みは当サイトで解決!!

HOME > C# 2005 Tips > コントロール > ListBox Tips メニュー

11.選択されている項目のインデックスを取得する

UPDATE:2006/09/10 

<< 前のTips  次のTips >>

 

 ListBox上で選択されてる項目のインデックスを取得するには、SelectedIndexプロパティを使用します。SelectedIndexプロパティは0から始まるインデックスを返します。複数選択リストボックスの場合には最初に選択されているアイテムのインデックスを返します。また、選択されているすべての項目のインデックスを取得するにはSelectedIndicesプロパティを使用します。

 
サンプル1
private void Form1_Load(object sender, EventArgs e)
{
    string[] strData = { "A", "B", "C", "D", "E" };
    
    //リストボックスにアイテムを追加
    listBox1.Items.AddRange(strData);

    //複数項目選択可能にする
    listBox1.SelectionMode = SelectionMode.MultiSimple;
}
 
private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show((listBox1.SelectedIndex + 1).ToString() + "番目が選択されています。");
}


 
サンプル2
private void Form1_Load(object sender, EventArgs e)
{
    string[] strData = { "A", "B", "C", "D", "E" };
    
    //リストボックスにアイテムを追加
    listBox1.Items.AddRange(strData);

    //複数項目選択可能にする
    listBox1.SelectionMode = SelectionMode.MultiSimple;
}
 
private void button1_Click(object sender, EventArgs e)
{
    int i;
    string strMsg = "";

    for (i = 0; i < listBox1.SelectedIndices.Count; i++)
    {
        strMsg += (listBox1.SelectedIndices[i] + 1).ToString() + "番目\n";
    }

    strMsg += "が選択されています。";

    MessageBox.Show(strMsg);
}