2014-01-25 4 views
0

У меня есть textbox в моих windowform. Я хочу, чтобы он предложил данные от database. для этого я написал этот код, но он не работает.Autocomplete не предлагает данные

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 случае нагрузки. txtCategory - это имя моего textbox. , где проблема

+0

что ваша строка соединения varible 'str' значение? –

ответ

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; 
Смежные вопросы