繁体   English   中英

如何在WPF应用程序中使用C#制作类似Google的自动完成文本框?

[英]How to make a google-like auto complete textbox with C# in a WPF application?

我试图找到一个解决方案,但我找不到我要搜索的内容。 所以这是我的问题。 我想要一个带文本框的谷歌行为。 当我输入“dum”时,它应该在数据库中找到dummy并将其显示为文本框下的选项。 它应该是可选择的。 我不使用ASP.net或任何其他东西。 只是纯粹的C#。

谢谢你的帮助!

AutoCompleteSource属性设置为字符串列表,并将AutoCompleteSource设置为CustomSource ,将AutoCompleteModeSuggest

我的解决方案

private void tbautocomplete_TextChanged(object sender, EventArgs e)
{
    AutoCompleteStringCollection namecollection = new AutoCompleteStringCollection();
    SqlConnection con = new SqlConnection(@"Data Source=88888;Initial Catalog=contrynames;Integrated Security=True");
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "SELECT  distinct(person_Firstname+''+person_Lastname) AS name FROM persondetails WHERE name Like '%'+@name+'%'";
    con.Open();
    SqlDataReader rea = cmd.ExecuteReader();
    if (rea.HasRows == true)
    {
        while (rea.Read())
        namecollection.Add(rea["name"].ToString());            
    }
    rea.Close();

    tbautocomplete.AutoCompleteMode = AutoCompleteMode.Suggest;
    tbautocomplete.AutoCompleteSource = AutoCompleteSource.CustomSource;
    tbautocomplete.AutoCompleteCustomSource = namecollection;

对于自动完成文本框,首先取一个文本框和一个宽度相同的列表框。然后创建一些事件,如textchanged,previewtextKeydown,listbox selectionchanged。你得到你的解决方案。 有关详细信息,请参阅此示例
autocompleteTextBox

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM