C# “自动完成”不会显示数据

C# “自动完成”不会显示数据,c#,winforms,autocomplete,textbox,C#,Winforms,Autocomplete,Textbox,我的窗口窗体中有一个文本框。 我希望它能提供数据库中的数据。为此,我编写了这段代码,但它不起作用 public void AutoComplete() { try { SqlConnection con = new SqlConnection(str); con.Open(); SqlCommand cmd = new SqlCommand("select di

我的窗口窗体中有一个文本框。 我希望它能提供数据库中的数据。为此,我编写了这段代码,但它不起作用

public void AutoComplete()
        {
            try
            {
            SqlConnection con = new SqlConnection(str);
            con.Open();
            SqlCommand cmd = new SqlCommand("select distinct CategoryName FROM Category", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds, "Category");
            AutoCompleteStringCollection autoComp = new AutoCompleteStringCollection();
            int i = 0;
            for (i = 0; i < ds.Tables[0].Rows.Count;i++)
            {
                autoComp.Add(ds.Tables[0].Rows[i]["CategoryName"].ToString());
            }
            txtCategory.AutoCompleteSource = AutoCompleteSource.CustomSource;
            txtCategory.AutoCompleteCustomSource = autoComp;
            txtCategory.AutoCompleteMode = AutoCompleteMode.Suggest;
            con.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
我在表单加载事件中调用了这个方法。 txtCategory是我的文本框的名称。 问题出在哪里

试试这个

AutoCompleteStringCollection autoComp = new AutoCompleteStringCollection();
try
{
 SqlConnection con = new SqlConnection(@"server=localhost;database=sakila;userid=root;password=password;");
 SqlCommand cmd = new SqlCommand();
 cmd.Connection = con;
 cmd.CommandType = CommandType.Text;
 cmd.CommandText = "select distinct CategoryName FROM Category";
 con.Open();
 SqlDataReader rea = cmd.ExecuteReader();

 if (rea.HasRows == true)
 {
    while (rea.Read())
    {
      autoComp.Add(rea.GetString(0));
    }
    rea.Close();
 }
 catch (SqlException err)
 {
   MessageBox.Show("Error: " + err.ToString());
 }

 this.txtCategory.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
 this.txtCategory.AutoCompleteSource = AutoCompleteSource.CustomSource;
 this.txtCategory.AutoCompleteCustomSource = autoComp;

您的连接字符串变量str值是多少?