我有这行代码可以帮助我自动填写文本框。它确实建议但在我选择之前,它会在2秒内消失。在选择一个选项之前,如何让它保持不变?
void autoComplete()
{
searchTxtBox.AutoCompleteMode = AutoCompleteMode.Suggest;
searchTxtBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection coll = new AutoCompleteStringCollection();
SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=Cmanager;Integrated Security=True");
SqlCommand comm = new SqlCommand("Select * from NEWMEMBER", con);
SqlDataReader reader;
try
{
con.Open();
reader = comm.ExecuteReader();
while (reader.Read())
{
if (nameRadBtn.Checked)
{
string databaseAuto = (reader["Surname"].ToString());
coll.Add(databaseAuto);
}
if (idRadBtn.Checked)
{
string databaseAuto = (reader["MemberID"].ToString());
coll.Add(databaseAuto);
}
if (deptRadBtn.Checked)
{
string databaseAuto = (reader["DeptID"].ToString());
coll.Add(databaseAuto);
}
}
con.Close();
}
catch (Exception)
{
throw;
}
searchTxtBox.AutoCompleteCustomSource = coll;
}
private void searchTxtBox_KeyUp(object sender, KeyEventArgs e)
{
autoComplete();
}
答案 0 :(得分:0)
您需要使用TextChanged()
事件而不是KeyUp
。此外,您不需要在使用之前绑定AutoComplete source
。但在使用自动完成之前设置textbox
属性,并为AutoCompleteStringCollection
试试这个解决方案,
// Private field
private AutoCompleteStringCollection coll = new AutoCompleteStringCollection();
public Form1(){
InitializeComponent();
....
searchTxtBox.AutoCompleteMode = AutoCompleteMode.Suggest;
searchTxtBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
void autoComplete()
{
SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=Cmanager;Integrated Security=True");
SqlCommand comm = new SqlCommand("Select * from NEWMEMBER", con);
SqlDataReader reader;
try
{
con.Open();
reader = comm.ExecuteReader();
while (reader.Read())
{
if (nameRadBtn.Checked)
{
string databaseAuto = (reader["Surname"].ToString());
coll.Add(databaseAuto);
}
if (idRadBtn.Checked)
{
string databaseAuto = (reader["MemberID"].ToString());
coll.Add(databaseAuto);
}
if (deptRadBtn.Checked)
{
string databaseAuto = (reader["DeptID"].ToString());
coll.Add(databaseAuto);
}
}
con.Close();
}
catch (Exception)
{
throw;
}
}
private void searchTxtBox_TextChanged(object sender, KeyEventArgs e)
{
col.clear() // Clear older entries
autoComplete();
searchTxtBox.AutoCompleteCustomSource = coll;
}