使用mysql作为数据库的文本框自动完成

时间:2011-06-14 10:11:42

标签: c# mysql winforms autocomplete textbox

我正在尝试使用下面的代码执行文本框自动完成,但它会给出错误

ERROR :"Object reference not set to an instance of an object"

在这一行:

for (int count = 0; count < dt.Rows.Count; count++)

任何人都可以帮助我吗?

private void tbMemberName_TextChanged_1(object sender, EventArgs e)
{
    tbMemberName.AutoCompleteMode = AutoCompleteMode.Suggest;
    tbMemberName.AutoCompleteSource = AutoCompleteSource.CustomSource;
    AutoCompleteStringCollection namec = new AutoCompleteStringCollection();

    //string search ="%"+ tbMemberName.Text +"%";
    //string @Name = tbMemberName.Text; 
    String sql =
        @"SELECT DISTINCT(member_Firstname +''+ member_Lastname) AS Name FROM members WHERE Name  Like '%'+tbMemberName.Text+'%'";
    DataTable dt = MemberFormHelper.GetData(sql, mf);
    if (dt.Rows.Count >= 0)
    {
        for (int count = 0; count < dt.Rows.Count; count++)
        {
            namec.Add(dt.Rows[count][Name].ToString());
        }
    }
    tbMemberName.AutoCompleteCustomSource = namec;
}

3 个答案:

答案 0 :(得分:1)

dt为null,为多数(除非你在ur表中有一个记录,其名称为'tbMemberName.Text')...我想是的 - tbMemberNameTextBox ,所以如果你试图将其值传递给sql字符串而不是

@"SELECT DISTINCT(member_Firstname +''+ member_Lastname) AS Name FROM members WHERE Name Like '%'+tbMemberName.Text+'%'";

你必须写

@"SELECT DISTINCT(member_Firstname +''+ member_Lastname) AS Name FROM members WHERE Name Like '%"+tbMemberName.Text+"%'";

你刚刚误用了引号。

答案 1 :(得分:1)

我根据msdn microsoft和先生P.K.的代码使用了这段代码。我认为你应该考虑这个

首先,我将这些代码插入form_load
中 例如:

this.cmbSchool.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
this.cmbSchool.AutoCompleteSource = AutoCompleteSource.CustomSource;

要访问我的示例中的textchanged属性,我使用了comboBox而不是Textbox(我将它们插入到表单之外,并将其用作通用var,以后可以通过combobox1_textchange访问)

AutoCompleteStringCollection collection = new AutoCompleteStringCollection();


如果您使用的是Mysql,我使用它(也插入form_load)将数据保存在集合中

        string querySelect = "SELECT * FROM tblschools";
        MySqlCommand commandSelect = new MySqlCommand(querySelect, connectionMain);
        MySqlDataReader reader = commandSelect.ExecuteReader();
        while (reader.Read())
        {
            string type = reader[1].ToString();
            cmbSchool.Items.Add(type); //data inserted in combobox list (dropdownstyle in c# dropdown) so that I can still type
            collection.Add(type); //data inserted in collection so that it will be autocomplete when you type keywords
        }
        reader.Close();

然后最后一步是在cmbSchool_TextChanged

中插入此代码
this.cmbSchool.AutoCompleteCustomSource = collection; //everytime you type it will initiate and gather data from the collection

P.S。这是我第一次发布抱歉我的解释和错误的编码,但希望它有所帮助

答案 2 :(得分:0)

我认为DT必须为null,并且它实际上是for循环上面的行