65.9K
CodeProject 正在变化。 阅读更多。
Home

自动完成组合框

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (24投票s)

2006年11月8日

CPOL
viewsIcon

165061

downloadIcon

13137

一篇关于自动完成 ComboBox 的文章。

Sample Image - AutoCompleteComboBox.gif

引言

这是一个简单的代码片段,用于创建一个自动完成 ComboBox

使用代码

用法:ComboBoxKeyPress 事件处理程序中调用函数 AutoComplete

AutoComplete(ComboBox cb, System.Windows.Forms.KeyPressEventArgs e, bool blnLimitToList)

// AutoComplete
public void AutoComplete(ComboBox cb, System.Windows.Forms.KeyPressEventArgs e)
{
    this.AutoComplete(cb, e, false);
}

public void AutoComplete(ComboBox cb, 
       System.Windows.Forms.KeyPressEventArgs e, bool blnLimitToList)
{
    string strFindStr = "";

    if (e.KeyChar == (char)8) 
    {
        if (cb.SelectionStart <= 1) 
        {
            cb.Text = "";
            return;
        }

        if (cb.SelectionLength == 0)
            strFindStr = cb.Text.Substring(0, cb.Text.Length - 1);
        else 
            strFindStr = cb.Text.Substring(0, cb.SelectionStart - 1);
    }
    else 
    {
        if (cb.SelectionLength == 0)
            strFindStr = cb.Text + e.KeyChar;
        else
            strFindStr = cb.Text.Substring(0, cb.SelectionStart) + e.KeyChar;
    }

    int intIdx = -1;

    // Search the string in the ComboBox list.

    intIdx = cb.FindString(strFindStr);

    if (intIdx != -1)
    {
        cb.SelectedText = "";
        cb.SelectedIndex = intIdx;
        cb.SelectionStart = strFindStr.Length;
        cb.SelectionLength = cb.Text.Length;
        e.Handled = true;
    }
    else
    {
        e.Handled = blnLimitToList;
    }
}

历史

  • 发布于 2006年11月8日。
© . All rights reserved.