【问题标题】:set autocomplete in a textbox在文本框中设置自动完成
【发布时间】:2014-03-10 18:04:11
【问题描述】:

我在 Windows 窗体应用程序中有一个文本框(名为 textbox1)。我有一个名为 nn.sdf 的数据库,我想将其用作自动完成的来源。每当用户在 textbox1 中输入时,它都会显示来自数据库的建议,与用户给出的输入文本相匹配。所以我将我的代码放入textBox1_TextChangedproperty。我的代码在这里:

 private void textBox1_TextChanged(object sender, EventArgs e)
    {
        AutoCompleteStringCollection namesCollection = new AutoCompleteStringCollection();
        SqlCeConnection con = new SqlCeConnection(@"Data Source=C:\Users\Imon-Bayazid\Documents\nn.sdf");
        con.Open();
        SqlCeCommand cmnd = con.CreateCommand();
        cmnd.CommandType = CommandType.Text;
        cmnd.CommandText = "SELECT top(10)  english FROM dic";        
        SqlCeDataReader dReader;
        dReader = cmnd.ExecuteReader();

        if (dReader.Read())
        {
            while (dReader.Read())
                namesCollection.Add(dReader["english"].ToString());
        }
        else
        {
            MessageBox.Show("Data not found");
        }
        dReader.Close();

        textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
        textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
        textBox1.AutoCompleteCustomSource = namesCollection;
    }

但它只显示前 10 个数据。我知道我的行有问题

  cmnd.CommandText = "SELECT top(10)  english FROM dic";// english is my column name and dic is my table name   

我不知道 cmnd.CommandText 应该是什么。每当用户在 textbox1 中输入任何内容时,我都想要自动提示。 我该怎么做???

【问题讨论】:

    标签: c# autocomplete


    【解决方案1】:

    如您所知,CommandText 应该(或可能)是一条 SQL 语句。试试下面的

    int fetchAmount = 10;
    string userInput = "abc";
    cmnd.CommandText = string.Format("SELECT top ({0}) english FROM dic WHERE english like '{1}%'",
        fetchAmount.ToString(), userInput);
    

    LIKE 是一个比较文本的 SQL 命令。因此,在您的情况下,您希望所有结果都以用户输入的文本开头。

    现在,在有人接手我的案子之前,我知道这不是最好的方法。直接在 SQL 语句中输入值会使您对 SQL 注入敞开大门。我强烈建议您学习并实施存储过程来与数据库进行任何交互。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      • 2011-04-18
      • 2010-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多