AutoComplete ComboBox in DataGridView using C#.net Windows Application

Here is a quick example of how to use an AutoComplete ComboBox in DataGridView in a Windows Application.

  1. Create one Windows Application and add DataGridView from toolbox to design.
  2. Now create two DataGridViewComboBoxColumns and add them to the DataGridView:
    public void ComboList1()
    {
        DataGridViewComboBoxColumn combo1 = new DataGridViewComboBoxColumn();
        combo1.HeaderText = "Country";
        combo1.Items.Add("Antarctica");
        combo1.Items.Add("Belgium");
        combo1.Items.Add("Canada");
        combo1.Items.Add("Finland");
        combo1.Items.Add("Albania");
        combo1.Items.Add("India");
        combo1.Items.Add("Barbados");
        dataGridView1.Columns.Add(combo1);
    }
    public void ComboList2()
    {
        DataGridViewComboBoxColumn combo2 = new DataGridViewComboBoxColumn();
        combo2.HeaderText = "Types of Jobs";
        combo2.Items.Add("Accounting");
        combo2.Items.Add("HR");
        combo2.Items.Add("Finance");
        combo2.Items.Add("Transportation");
        combo2.Items.Add("Testing");
        dataGridView1.Columns.Add(combo2);
    }
  3. Call both these methods from the Form Constructor.
  4. Now Click on DataGridView and generate EditingControlShowing event and write the folllowing code in it:
    if (e.Control is DataGridViewComboBoxEditingControl)
    {
        ((ComboBox)e.Control).DropDownStyle = ComboBoxStyle.DropDown;
        ((ComboBox)e.Control).AutoCompleteSource = AutoCompleteSource.ListItems;
        ((ComboBox)e.Control).AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
    }
    This will work for all comboBoxes which are present in the DataGridView.

    textbox1.gif

    The AutoCompleteMode and AutoCompleteSource properties create a ComboBox that automatically completes input strings by comparing the prefix being entered to the prefixes of all strings in a maintained source. This is useful for ComboBox controls in which URLs, addresses, file names, or commands will be frequently entered. If there are duplicate entries in the maintained source, automatic completion behaves unpredictably.


Similar Articles