いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

コンボボックスの自動補完機能(ComboBox, AutoCompleteMode, AutoCompleteSource)


コンボボックスコントロールには、入力された値から該当するデータを
補完する機能があります。


以下のプロパティを使用します。

  • AutoCompleteMode
  • AutoCompleteSource


以下サンプルです。

// vim:set ts=4 sw=4 et ws is nowrap ft=cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

namespace Gsf.Samples.WinForms{

    /// 
    /// コンボボックスのモデルとして使用するクラスです。
    /// 
    class SampleKeyValuePair{
        string _key;
        string _value;

        public SampleKeyValuePair(string key, string aValue){
            _key   = key;
            _value = aValue;
        }

        public string Key{
            get{
                return _key;
            }
            set{
                _key = value;
            }
        }

        public string Value{
            get{
                return _value;
            }
            set{
                _value = value;
            }
        }
    }
    
    /// 
    /// コンボボックスの自動補完機能についてのサンプルです。
    /// 
    /// 
    /// コンボボックスにて、自動補完機能を有効にするには、
    /// 以下のプロパティに値を設定します。
    ///
    /// -AutoCompleteMode
    /// -AutoCompleteSource
    /// 
    public class ComboBoxAutoCompleteSample : Form{

        public ComboBoxAutoCompleteSample(){
            InitializeComponent();
        }

        protected void InitializeComponent(){
            ComboBox c = new ComboBox();

            c.DataSource    = GetDataSource();
            c.DisplayMember = "Key";
            c.ValueMember   = "Value";

            //
            // オートコンプリートのモード指定を行います。
            //
            // Suggestの場合は、候補のみが表示されます。
            // SuggestAppendの場合は、さらに一意に確定している部分を自動で追加してくれます。
            //
            c.AutoCompleteMode   = AutoCompleteMode.SuggestAppend;
            //
            // コンプリート元のデータソースを指定します。
            //
            // ListItemsは、コンボボックス自身が持つデータリストを
            // 補完対象とします。
            //
            c.AutoCompleteSource = AutoCompleteSource.ListItems;

            Controls.Add(c);
            Size = new System.Drawing.Size(150, 100);
        }

        private BindingSource GetDataSource(){
            BindingSource s = new BindingSource();

            s.DataSource = typeof(SampleKeyValuePair);

            s.Add(new SampleKeyValuePair("value1", "gsf_zero1"));
            s.Add(new SampleKeyValuePair("value2", "gsf_zero2"));
            s.Add(new SampleKeyValuePair("value3", "gsf_zero3"));

            return s;
        }

        [STAThread]
        static void Main(){
            Application.EnableVisualStyles();
            Application.Run(new ComboBoxAutoCompleteSample());
        }
    }
}

上記サンプルを実行すると、コンボボックスに値を入力した時点で
補完機能が働き、候補が表示されます。