Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autocomplete AND preventing new input - combobox

How can I allow the users of my program to type in a value and have it auto-complete, however, I also what to prevent them from entering new data because it would cause the data to be unfindable (unless you had direct access to the database).

Does anyone know how to do this?

The reasoning behind not using just a dropdown style combobox is because entering data by typing it is and then refusing characters that are not part of an option in the list is because it's easier on the user.

If you have used Quickbook's Timer, that is the style of comboboxes I am going for.

like image 220
Malfist Avatar asked Jan 30 '09 15:01

Malfist


2 Answers

Kudos to BFree for the help, but this is the solution I was looking for. The ComboBox is using a DataSet as it's source so it's not a custom source.

    protected virtual void comboBoxAutoComplete_KeyPress(object sender, KeyPressEventArgs e) {
        if (Char.IsControl(e.KeyChar)) {
            //let it go if it's a control char such as escape, tab, backspace, enter...
            return;
        }
        ComboBox box = ((ComboBox)sender);

        //must get the selected portion only. Otherwise, we append the e.KeyChar to the AutoSuggested value (i.e. we'd never get anywhere)
        string nonSelected = box.Text.Substring(0, box.Text.Length - box.SelectionLength);

        string text = nonSelected + e.KeyChar;
        bool matched = false;
        for (int i = 0; i < box.Items.Count; i++) {
            if (((DataRowView)box.Items[i])[box.DisplayMember].ToString().StartsWith(text, true, null)) {
                matched = true;
                break;
            }
        }

        //toggle the matched bool because if we set handled to true, it precent's input, and we don't want to prevent
        //input if it's matched.
        e.Handled = !matched;
    }
like image 150
Malfist Avatar answered Sep 18 '22 16:09

Malfist


This is my solution, I was having the same problem and modify your code to suit my solution using textbox instead of combobox, also to avoid a negative response after comparing the first string had to deselect the text before comparing again against autocomplet list, in this code is an AutoCompleteStringCollection shiper, I hope this solution will help

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
  String text = ((TextBox)sender).Text.Substring(
    0, ((TextBox)sender).SelectionStart) + e.KeyChar;
  foreach(String s in this.shippers)
    if (s.ToUpperInvariant().StartsWith(text.ToUpperInvariant()) ||
      e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Delete)
        return;                    

  e.Handled = true;
}
like image 25
Yosvani Quinones Avatar answered Sep 19 '22 16:09

Yosvani Quinones