A combo-box is a window form control that developers use for better user experience. It’s a combination of a dropdown list and a text box. It allows the user to select the desired item or directly type a value into the control.

To better understand this tutorial, you should know following C# programming areas:

In some cases, the autocomplete functionality can improve the user experience, especially when the combo box has too many items to select from it.  Therefore the example below of how to implement the autocomplete functionality using C# and SQL Server Database.

Auto-Complete ComboBox

First, create a SQL Server table, name it, and then add data to it as shown below:

Table-Programming-Language-Design

Table-Programming-Language-Data

Create a Desktop Application and add a ComboBox control to the default form:

AutoComplete ComboBox Win Form

Use the code below to bind the Combobox:

private void frm_Load(object sender, EventArgs e)
       {
           try
           {

               String strconn = "Data Source=YourSource;Initial Catalog=DataBaseName;Integrated Security=True;Pooling=False";
               SqlConnection conn = new SqlConnection(strconn);
               conn.Open();
               String strSQL;
               SqlCommand cmd;
               SqlDataAdapter da = new SqlDataAdapter();

               // Fill DataTable

               DataTable dt = new DataTable() ;

               strSQL = "Select * From ProgrammingLanguage Order by LanguageName ASC";
               cmd = new SqlCommand(strSQL, conn);
               cmd.CommandType = CommandType.Text;
               da.SelectCommand = cmd;
               da.Fill(dt);
               conn.Close();

               //Bind ComboBox
               cbAutoComplete.DataSource = dt;
               cbAutoComplete.DisplayMember = "LanguageName";

           }
           catch (Exception ex)
           {
               MessageBox.Show(ex.Message);
           }
       }

Furthermore, add the following code to the KeyPress event of the ComboBox:

private void cbAutoComplete_KeyPress(object sender, KeyPressEventArgs e)
{
    cbAutoComplete.DroppedDown = true;
    if (char.IsControl(e.KeyChar))
    {
        return;
    }
    string str = cbAutoComplete.Text.Substring(0, cbAutoComplete.SelectionStart) + e.KeyChar;
    Int32 index = cbAutoComplete.FindStringExact(str);
    if (index == -1)
    {
        index = cbAutoComplete.FindString(str);
    }
    this.cbAutoComplete.SelectedIndex = index;
    this.cbAutoComplete.SelectionStart = str.Length;
    this.cbAutoComplete.SelectionLength = this.cbAutoComplete.Text.Length - this.cbAutoComplete.SelectionStart;
    e.Handled = true;
}

Run the application.

autoComplete-Combo Result

 

Last modified: March 8, 2019

Comments

Write a Reply or Comment

Your email address will not be published.