ListBoxに要素を追加するコードを紹介します。
UI
Windowsフォームアプリケーションで下図のフォームを作成します。(実際に利用するのは[Add]ボタンのみです。)
コード
以下のコードを記述します。
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メソッドを利用します。引数には要素のキャプションとなるテキスト値を与えます。
実行結果
プロジェクトを実行します。下図のウィンドウが表示されます。
[Add]ボタンをクリックします。ListBoxに要素が5つ追加されました。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2013-01-25