VB.NET, C#, PowerShellを使用しているエンジニアのためのサイト。
基本的な使用方法から開発で役立つTipsまで幅広く取り扱っています。
ListBox上で選択されてる項目のインデックスを取得するには、SelectedIndexプロパティを使用します。SelectedIndexプロパティは0から始まるインデックスを返します。複数選択リストボックスの場合には最初に選択されているアイテムのインデックスを返します。また、選択されているすべての項目のインデックスを取得するにはSelectedIndicesプロパティを使用します。
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() + "番目が選択されています。"); }
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); }