自动填充功能不会提示数据

时间:2014-01-25 16:09:03

标签: c# winforms autocomplete textbox

我的textbox window中有一个form。 我希望它应该建议来自database的数据。为此我编写了这段代码,但它没有用。

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);
            }
        }

我在form load事件上调用了这个方法。 txtCategory是我textbox的名称。 问题在哪里

1 个答案:

答案 0 :(得分:0)

试试这个

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;