動くコード図鑑技術記事現場の渡り方キャリア論すべての記事About
C#

パターン4: GetValues / GetNamesでComboBoxバインド

出典: C# Enum 完全ガイド — Description 属性 / [Flags] / 数値変換の使い分け5パターンパターン4: GetValues / GetNamesでComboBoxバインド

パターン4: GetValues / GetNamesでComboBoxバインド (csharp)#d673233cfac5
using System;
using System.Linq;
using System.Windows.Forms;
 
public class StatusForm : Form
{
    private ComboBox statusComboBox;
 
    public StatusForm()
    {
        statusComboBox = new ComboBox();
        statusComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
 
        // Enumの全値を取得してComboBoxにバインド
        var items = Enum.GetValues(typeof(ProductStatus))
            .Cast<ProductStatus>()
            .Select(s => new
            {
                Value = (int)s,
                Display = s.GetDescription()// Description属性で表示
            })
            .ToList();
 
        statusComboBox.DataSource = items;
        statusComboBox.ValueMember = "Value";
        statusComboBox.DisplayMember = "Display";
 
        Controls.Add(statusComboBox);
    }
}
▸ この snippet は実行結果未収録
▸ 実行結果は未収録です
  • id: #d673233cfac5
  • lines: 30
  • extracted: 2026-06-10

Source収録記事

この snippet は記事の「パターン4: GetValues / GetNamesでComboBoxバインド」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。

同じ記事から

7
図鑑トップ