我的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
的名称。
问题在哪里
答案 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;