如何在winforms桌面应用程序中创建自动完成文本框

时间:2011-01-07 20:21:54

标签: c# winforms autocomplete textbox desktop-application

我有一个单词列表。该列表包含大约100-200个文本字符串(实际上是地铁站的名称)。

我想制作一个自动完成的文本框。例如,用户按'N'字母,然后出现(结束)适当选项(仅一个选项)。必须选择结尾。

怎么做?

PS1:我猜,有一个文本框控件,其属性如下:

List<string> AppropriateOptions{/* ... */}
PS2:对不起我的英语。如果你不明白 - &gt;问我,我会尽力解释!

6 个答案:

答案 0 :(得分:17)

为了防止@ leniel的链接断开,这里有一些代码可以解决这个问题:

AutoCompleteStringCollection allowedTypes = new AutoCompleteStringCollection();
allowedTypes.AddRange(yourArrayOfSuggestions);
txtType.AutoCompleteCustomSource = allowedTypes;
txtType.AutoCompleteMode = AutoCompleteMode.Suggest;
txtType.AutoCompleteSource = AutoCompleteSource.CustomSource;

答案 1 :(得分:1)

使用ComboBox而不是TextBox。以下示例将自动完成,匹配文本的任何部分,而不仅仅是起始字母。

这应该是一个完整的表单,只需添加自己的数据源和数据源列名。 : - )

using System;
using System.Data;
using System.Windows.Forms;

public partial class frmTestAutocomplete : Form
{

private DataTable maoCompleteList;
private const string MC_DISPLAY_COL = "name";
private const string MC_ID_COL = "id";

public frmTestAutocomplete()
{
    InitializeComponent();
}

private void frmTestAutocomplete_Load(object sender, EventArgs e)
{

        maoCompleteList = oData.PurificationRuns;
        maoCompleteList.CaseSensitive = false; //turn off case sensitivity for searching

        testCombo.DisplayMember = MC_DISPLAY_COL;
        testCombo.ValueMember = MC_ID_COL; 
        testCombo.DataSource = GetDataTableFromDatabase();
        testCombo.SelectedIndexChanged += testCombo_SelectedIndexChanged;
        testCombo.KeyUp += testCombo_KeyUp; 
}


private void testCombo_KeyUp(object sender, KeyEventArgs e)
{
    //use keyUp event, as text changed traps too many other evengts.

    ComboBox oBox = (ComboBox)sender;
    string sBoxText = oBox.Text;

    DataRow[] oFilteredRows = maoCompleteList.Select(MC_DISPLAY_COL + " Like '%" + sBoxText + "%'");

    DataTable oFilteredDT = oFilteredRows.Length > 0
                            ? oFilteredRows.CopyToDataTable()
                            : maoCompleteList;

    //NOW THAT WE HAVE OUR FILTERED LIST, WE NEED TO RE-BIND IT WIHOUT CHANGING THE TEXT IN THE ComboBox.

    //1).UNREGISTER THE SELECTED EVENT BEFORE RE-BINDING, b/c IT TRIGGERS ON BIND.
    testCombo.SelectedIndexChanged -= testCombo_SelectedIndexChanged; //don't select on typing.
    oBox.DataSource = oFilteredDT; //2).rebind to filtered list.
    testCombo.SelectedIndexChanged += testCombo_SelectedIndexChanged;


    //3).show the user the new filtered list.
    oBox.DroppedDown = true; //this will overwrite the text in the ComboBox, so 4&5 put it back.

    //4).binding data source erases text, so now we need to put the user's text back,
    oBox.Text = sBoxText;
    oBox.SelectionStart = sBoxText.Length; //5). need to put the user's cursor back where it was.


}

private void testCombo_SelectedIndexChanged(object sender, EventArgs e)
{

    ComboBox oBox = (ComboBox)sender;

    if (oBox.SelectedValue != null)
    {
        MessageBox.Show(string.Format(@"Item #{0} was selected.", oBox.SelectedValue));
    }
}

}

//=====================================================================================================
//      code from frmTestAutocomplete.Designer.cs
    //=====================================================================================================
    partial class frmTestAutocomplete

{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
    if (disposing && (components != null))
    {
        components.Dispose();
    }
    base.Dispose(disposing);
}

#region Windows Form Designer generated code

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
    this.testCombo = new System.Windows.Forms.ComboBox();
    this.SuspendLayout();
    // 
    // testCombo
    // 
    this.testCombo.FormattingEnabled = true;
    this.testCombo.Location = new System.Drawing.Point(27, 51);
    this.testCombo.Name = "testCombo";
    this.testCombo.Size = new System.Drawing.Size(224, 21);
    this.testCombo.TabIndex = 0;
    // 
    // frmTestAutocomplete
    // 
    this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.ClientSize = new System.Drawing.Size(292, 273);
    this.Controls.Add(this.testCombo);
    this.Name = "frmTestAutocomplete";
    this.Text = "frmTestAutocomplete";
    this.Load += new System.EventHandler(this.frmTestAutocomplete_Load);
    this.ResumeLayout(false);

}

#endregion

private System.Windows.Forms.ComboBox testCombo;

}

答案 2 :(得分:0)

您希望将TextBox.AutoCompleteSource设置为CustomSource,然后将所有字符串添加到AutoCompleteCustomSource属性,即StringCollection。然后你应该好好去。

答案 3 :(得分:0)

Leniel的答案链接在vb.net,感谢Joel的参赛作品。提供我的代码使其更明确:

private void InitializeTextBox()
{

    AutoCompleteStringCollection allowedStatorTypes = new AutoCompleteStringCollection();
    var allstatortypes = StatorTypeDAL.LoadList<List<StatorType>>().OrderBy(x => x.Name).Select(x => x.Name).Distinct().ToList();

    if (allstatortypes != null && allstatortypes.Count > 0)
    {
        foreach (string item in allstatortypes)
        {
            allowedStatorTypes.Add(item);
        }
    }

    txtStatorTypes.AutoCompleteMode = AutoCompleteMode.Suggest;
    txtStatorTypes.AutoCompleteSource = AutoCompleteSource.CustomSource;
    txtStatorTypes.AutoCompleteCustomSource = allowedStatorTypes;
}

答案 4 :(得分:0)

我想补充一点,TextBox的标准自动完成功能只能从字符串的开头起作用,因此如果你点击N,则只能找到以N开头的字符串。如果你想要更好的东西,你必须使用一些不同的控件或自己实现行为(即使用一些计时器对TextChanged事件做出反应以延迟执行,而不是过滤使用IndexOf(inputString)搜索的令牌列表,然后将AutoCompleteSource设置为过滤后的清单。

答案 5 :(得分:0)

使用组合框,设置其数据源或提供硬编码条目,但设置以下属性:

    AutoCompleteMode = Suggest;
    AutoCompleteSource = ListItems;