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); }
コメントを残す