本日は、Visual C#でリストボックスの操作について説明いたします。
Form内にリストボックスを2つ作成し、ListBox1内に複数の項目を設定し、
ボタンのクリックによって項目を移動したり、削除したりします。
完成のイメージです。
button1,button2によって、移動、削除が行われます。

ユーザフォームの作成
Visual Studio 2019を起動し、「新しいプロジェクトの作成」を起動します。

「Windowsフォームアプリケーション」をクリックします。

新しいプロジェクトを作成します。「作成」ボタンをクリックします。

Visual Studioが起動します。

「ツールボックス」を使い、リストボックスとボタンを2つずつ配置します。


コードを記載していきます。
まずは、フォームが起動したときのプログラムです。
配列を(Animal_Array)を用意し、値(馬、キリン、ライオン…)をセットしていきます。
次に配列をリストボックス1にセットします。
リストボックスは、マルチセレクトです。
private void Form1_Load(object sender, EventArgs e)
{
string[] Animal_Array = new string[] { "馬", "きりん", "ライオン", "ぞう", "いのしし", "犬", "猫" };
listBox1.Items.AddRange(Animal_Array);
listBox1.SelectionMode = SelectionMode.MultiSimple;
}
ここまででフォームを起動してみます。F5ボタンで起動できます。
リストボックスに値が入っています。

続いて、ボタンをクリックしたときの動きを記述します。
1.ボタン1をクリックした時の動作
リストボックス1内の選択された値をリストボックス2に追加します。
2.ボタン2をクリックした時の動作
リストボックス1内の選択された値をリストボックス1内から削除します。
private void button1_Click(object sender, EventArgs e)
{
foreach (Object Animallist in listBox1.SelectedItems)
{
listBox2.Items.Add(Animallist);
}
}
private void button2_Click(object sender, EventArgs e)
{
for (int i = listBox1.Items.Count-1;i >= 0;i--)
{
if (listBox1.GetSelected(i))
{
listBox1.Items.RemoveAt(i);
}
}
}
まとめ
リストボックスの値の操作について説明しました。