自动完成文本框,有两个选项在c# winform中搜索

本文关键字:选项 两个 搜索 winform 文本 | 更新日期: 2023-09-27 18:13:56

这是我在FormLoad -event上的代码

SqlDataReader dReader;
SqlConnection conn = new SqlConnection(MyClass.GlobalConn());
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
if (radioName.checked==true)
{           
    cmd.CommandText = "select RTRIM(Person_name) from MyTable order by Person_name";
}
else
{
    cmd.CommandText = "select RTRIM(Person_number) from MyTable order by Person_number";
}
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
    while (dReader.Read())
        namesCollection.Add(dReader[0].ToString());
}
else
{
    MessageBox.Show("Data not found");
}
dReader.Close();
tPT.AutoCompleteMode = AutoCompleteMode.Suggest;
tPT.AutoCompleteSource = AutoCompleteSource.CustomSource;
tPT.AutoCompleteCustomSource = namesCollection;
conn.Close();  

在文本框中输入时,我想要两个选项来填充自动完成文本框:

    按名称
  1. 按编号

然而,它不起作用。我已经在我的TextChanged -事件中尝试过了,但没有运气。有人能帮帮我吗?

自动完成文本框,有两个选项在c# winform中搜索

而不是使用可选的AutoCompleteSource将所有数据更新到一个数据源。这不会有任何问题,因为用户不需要选择选项,而是通过决定自己的选项来输入。

SqlDataReader dReader;
SqlConnection conn = new SqlConnection(MyClass.GlobalConn());
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text; 
cmd.CommandText = "select RTRIM(Person_name) from MyTable order by Person_name";
dReader = cmd.ExecuteReader();
cmd.CommandText = "select RTRIM(Person_number) from MyTable order by Person_number";
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
    while (dReader.Read())
        namesCollection.Add(dReader[0].ToString());
}
else
{
    MessageBox.Show("Data not found");
}
dReader.Close();
tPT.AutoCompleteMode = AutoCompleteMode.Suggest;
tPT.AutoCompleteSource = AutoCompleteSource.CustomSource;
tPT.AutoCompleteCustomSource = namesCollection;
conn.Close();

或者如果你想使用旧的选项

namesCollection.RemoveAll();
SqlDataReader dReader;
SqlConnection conn = new SqlConnection(MyClass.GlobalConn());
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text; 
namesCollection.RemoveAll();
if (radioName.checked==true)
{
    cmd.CommandText = "select RTRIM(Person_name) from MyTable order by Person_name";
}
else
{
    cmd.CommandText = "select RTRIM(Person_number) from MyTable order by Person_number";
}
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
    while (dReader.Read())
        namesCollection.Add(dReader[0].ToString());
}
else
{
    MessageBox.Show("Data not found");
}
dReader.Close();
tPT.AutoCompleteMode = AutoCompleteMode.Suggest;
tPT.AutoCompleteSource = AutoCompleteSource.CustomSource;
tPT.AutoCompleteCustomSource = namesCollection;
conn.Close();
通知

namesCollection.RemoveAll ();