目次

ListBox に要素を追加する

目次

ListBoxに要素を追加するコードを紹介します。

UI

Windowsフォームアプリケーションで下図のフォームを作成します。(実際に利用するのは[Add]ボタンのみです。)
ListBox に要素を追加する:画像1

コード

以下のコードを記述します。

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();
    }

    //Addボタン
    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");
    }
  }
}

解説

listBox1.Items.Add("Line:1");

にてリストボックスに要素を追加します。リストボックスに要素を追加するにはItemsプロパティのAddメソッドを利用します。引数には要素のキャプションとなるテキスト値を与えます。

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。
ListBox に要素を追加する:画像2

[Add]ボタンをクリックします。ListBoxに要素が5つ追加されました。
ListBox に要素を追加する:画像3

AuthorPortraitAlt
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
作成日: 2013-01-25
Copyright © 1995–2025 iPentec all rights reserverd.