0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【WindowsForm】ComboBoxの使い方

0
Last updated at Posted at 2025-09-21

環境

・Visual Studio 2022
・.Net 9.0
・Windows Forms

ComboBoxとは

設定された中から選択するドロップダウン、プルダウン機能が欲しいときに使えるコンポーネントです。

デザイン上での使い方

コンポーネントからComboBoxを選択して配置
スクリーンショット 2025-09-07 225003.png

事前に入力する内容が決まっている場合はItemsから設定できます。
スクリーンショット 2025-09-14 232158.png
スクリーンショット 2025-09-14 232234.png

デフォルトの設定だと、ComboBox内でキーボードから文字列を入力できますが、入力をさせたくない場合はDropDownStyleをDropDownListに変更します。
スクリーンショット 2025-09-14 232440.png

combobox.gif

コード上から設定

デザインではなくコード上からItemsを設定したい場合は以下のようになります。

   public partial class Form1 : Form
   {
       public Form1()
       {
           InitializeComponent();
           SetComboBoxItems();
       }

       private void SetComboBoxItems()
       {
           comboBox1.Items.Clear();
           // アイテムを追加
           comboBox1.Items.Add("Item 1");
           comboBox1.Items.Add("Item 2");
           comboBox1.Items.Add("Item 3");
           // 選択するアイテムを設定
           // comboBox1.SelectedIndex = -1; にすると未選択状態になる
           comboBox1.SelectedIndex = 0;
           UpdateLabel();
       }

       private void UpdateLabel()
       {
           // 選択されたアイテムをラベルに表示
           this.label1.Text = $"Selected: {comboBox1.SelectedItem}";
       }

       /// <summary>
       /// ComboBoxの選択アイテムが変更されたときのイベント
       /// </summary>
       private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
       {
           UpdateLabel();
       }
   }

combobox2.gif

選択したアイテムが変化したことを検知できるSelectedIndexChangedが使われやすいイベントだと思います。

デザイン上からItemsを設定する場合は文字列として登録されますが、コード上から追加した場合はその追加した型で登録されます。
なのでItemsの中から検索などを行うとき、デザイン上から追加したものとコード上で文字列以外で登録した場合は複数の型のデータが混在することになるので判定部分の処理は注意が必要です。

株式会社ONE WEDGE

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?