简体   繁体   中英

Autocomplete doesn't suggesting data

i have a textbox in my window form . i want it should suggest data from the database . for this purpose i have written this code , but it doesn't working .

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

and i called this method on form load event. txtCategory is name of my textbox . where is the problem

Try this

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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