C#如何使用AutoCompleteSource

时间:2018-08-26 05:36:29

标签: c# visual-studio winforms sql-server-2008

我这里有一个无法解决的问题。我的Windows应用程序中有一个文本框。在该文本框中,我想显示一个建议。在我的数据库中,我具有列名“ Codeitem”,它是整数。我想在我的texbox上显示此值,但我不知道该怎么做。任何帮助的人。非常感谢

AutoCompleteStringCollection Collection = new AutoCompleteStringCollection
  private void SIMSProduct_Load(object sender, EventArgs e)
    {

        AddingProduct();

        using (var con = SQLConnection.GetConnection())
        {


            var select = new SqlCommand("Select Codeitem from employee_product", con);
            var reader = select.ExecuteReader();

            while (reader.Read())
            {
                Collection.Add(reader.GetString(0));
            }       

        }

    }
private void txt_code_TextChanged(object sender, EventArgs e)
    {

        txt_code.AutoCompleteCustomSource = Collection;
        txt_code.AutoCompleteMode = AutoCompleteMode.Append;
        txt_code.AutoCompleteSource = AutoCompleteSource.CustomSource;

    }

2 个答案:

答案 0 :(得分:1)

添加以下两行: txt_code.AutoCompleteMode = AutoCompleteMode.Append; txt_code.AutoCompleteSource = AutoCompleteSource.CustomSource;

您添加的位置: txt_code.AutoCompleteCustomSource =集合;

作为旁注,请确保对阅读器使用(),然后选择。使用完后应将SqlCommands和SqlDataReaders丢弃。

答案 1 :(得分:0)

您需要在此处阅读文档:https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.textbox.autocompletemode?redirectedfrom=MSDN&view=netframework-4.7.2#System_Windows_Forms_TextBox_AutoCompleteMode,并且在这里已经回答了问题的答案:C#: How to use custom autocomplete source for textbox,您忘记添加:

AutoCompleteMode = AutoCompleteMode.SuggestAppend;
AutoCompleteSource = AutoCompleteSource.CustomSource;