目次

ListBoxで指定したキャプションを持つ要素を削除する - C#

ListBoxで指定したキャプションを持つ要素を削除するコードを紹介します。

UI

下図のUIを作成します。ListBoxとButtonを配置します。(Buttonは3つ配置してありますが、button1とbutton3しか使用しません)

コード

下記のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ListBoxDemo
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      listBox1.Items.Add("Line:1");
      listBox1.Items.Add("Line:2");
      listBox1.Items.Add("Line:3");
      listBox1.Items.Add("Line:4");
      listBox1.Items.Add("Line:5");
    }

    private void button3_Click(object sender, EventArgs e)
    {
      listBox1.Items.Remove("Line:2");
    }
  }
}

解説

ListBoxで指定したキャプションの要素を削除する場合は ListBox.Items.Remove()メソッドの引数にキャプションの文字列を与えて呼び出すます。上記の例では
listBox1.Items.Remove("Line:2");
にて"Line:2"を与えて呼び出しているため、"Line:2"のキャプションを持つ要素がListBoxから削除されます。

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


"button1"を押します。ListBoxに要素が追加されました。


ListBoxに要素が追加されている状態で[button3]を押します。"Line:2"のキャプションを持つ2番目の要素がListBoxから削除されました。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2012-07-13
iPentec all rights reserverd.