C# listBoxで選択されている値を削除する

C#で、RemoveAtメソッドを使用して、listBoxで選択されている値を削除するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Microsoft Visual Studio Community 2019 Version 16.7.1
RemoveAtメソッド使い方
RemoveAtメソッドを使用すると、listBoxで選択されている値を削除することが可能です。
1 2 3 4 5 |
// 選択されているitemのインデックス番号を取得 int index = listBox1.SelectedIndex; // 選択されているリストを削除 listBox1.Items.RemoveAt(index); |
サンプルコード
以下は、
「実行(button1)」ボタンをクリックして、listboxに値を追加した後に、
値を選択して、「実行(button2)」ボタンをクリックして選択した値を削除する
サンプルコードとなります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Windows.Forms; namespace FormTestApp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // item作成 for (int i = 0; i < 10; i++) { listBox1.Items.Add(i+"番目"); } } private void button2_Click(object sender, EventArgs e) { // 選択されているリストを削除 listBox1.Items.RemoveAt(listBox1.SelectedIndex); } } } |
カーソルが最終行に移動されていることが確認できます。

Removeメソッドの場合は、データの値をそのまま指定して削除することが可能です。
1 |
listBox1.Items.Remove("7番目"); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FormTestApp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // item作成 for (int i = 0; i < 10; i++) { listBox1.Items.Add(i+"番目"); } } private void button2_Click(object sender, EventArgs e) { listBox1.Items.Remove("7番目"); } } } |

また全て削除する場合は、以下となります。
1 |
listBox1.Items.Clear(); |
-
前の記事
javascript **を使用して累乗を計算する 2020.10.13
-
次の記事
javascript モジュールを作成する 2020.10.13
コメントを書く