Dynamically Fill AutoComplete Textbox from DataGridView



Introduction

I wanted to write code for looking up records in DataGridView for which I decided to use a simple auto-completing TextBox for easy search and dynamically refilled AutoCompleteStringCollection. This task can be accomplished through ComboBox, for which I had to make a roundtrip to the database server for the data that I have already gotten in the girdview. So I decided to use grid data for filling AutoCompleteStringCollection.

Any feedback is welcome as your feedback will improve quality.

Background

I need to write codes to search records in DataGridView control. So I gave different fields on which search can be made, and I also want to avoid roundtrip to database server for filling ComboBox.

Using the Codes

I add a panel control for serving as find form (which remain hidden until find buttons are clicked), and places two command buttons cmdFind and cmdCancelFind along with a ComboBox cmbFindFields which is filled with field names and a TextBox named txtCustomerFind.

Added following codes in the Validated Event of cmbFindFields.

private void cmbFindFields_Validated(object sender, EventArgs e)
{

 AutoCompleteStringCollection acCustomer = new 
 AutoCompleteStringCollection();
 foreach (DataGridViewRow row in dbDetail.Rows)
  {
    if (cmbFindFields.SelectedItem.ToString() == "Customer ID")
       {
                    txtCustomerFind.MaxLength = 5;
                    acCustomer.Add(row.Cells[0].Value.ToString());
       }
       else if (cmbFindFields.SelectedItem.ToString() == "Customer
                      Name")

        {
                    acCustomer.Add(row.Cells[1].Value.ToString());
                    txtCustomerFind.MaxLength = 40;
         }
        else
         {

                    acCustomer.Add(row.Cells[2].Value.ToString());
                    txtCustomerFind.MaxLength = 40;
           }

            } txtCustomerFind.Clear();
 txtCustomerFind.AutoCompleteMode = AutoCompleteMode.Suggest;
 txtCustomerFind.AutoCompleteSource = AutoCompleteSource.CustomSource;
 txtCustomerFind.AutoCompleteCustomSource = acCustomer;

 }

Whenever user selects a field AutoCompleteSource of txtCustomerFind is changed respectively.

Up Next
    Ebook Download
    View all
    Learn
    View all