ITEEDU

ComboBox组合框

组合框可以输入,列表框不可以输入只能选择。


AutoCompleteComboBox

.NET中没有自动完成组合框(AutoCompleteComboBox),但可以自己添加这个功能。

完成KeyPress和TextChange事件。

private bool controlKey = false;
private void OnTextChange(object sender, EventArgs e)
{

    if (comboBox1.Text != "" && !controlKey)
    {

        // Search for a matching entry.
        string matchText = comboBox1.Text;
        int match = comboBox1.FindString(matchText);

        // If a matching entry is found, insert it now.
        if (match != -1)
        {

            comboBox1.SelectedIndex = match;

            // Select the added text so it can be replaced
            // if the user keeps typing.
            comboBox1.SelectionStart = matchText.Length;
            comboBox1.SelectionLength = comboBox1.Text.Length - comboBox1.SelectionStart;
        }
    }
}

private void OnKeyPress(object sender, KeyPressEventArgs e)
{

    if (e.KeyChar == (int)Keys.Escape)
    {
        System.Console.WriteLine(e.KeyChar);

        // Clear the text.
        comboBox1.SelectedIndex = -1;
        comboBox1.Text = "";
        controlKey = true;
    }
    else if (Char.IsControl(e.KeyChar))
    {

        controlKey = true;
    }
    else
    {

        controlKey = false;
    }
}