使用mysql作为数据库自动完成文本框
本文关键字:文本 mysql 数据库 使用 | 更新日期: 2023-09-27 17:59:17
我正试图使用下面的代码自动完成文本框,但它给出了错误
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;
}
dt
为null,很长一段时间(除非您的表中有一条记录的名称为"tbMemberName.Text")…我想是这样-tbMemberName
是TextBox
,所以如果您试图将其值传递给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+"%'";
你刚才误用了引号。
我使用这个代码是基于微软和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();
然后最后一步是我在cmbSelect_TextChanged 中插入此代码
this.cmbSchool.AutoCompleteCustomSource = collection; //everytime you type it will initiate and gather data from the collection
附言:这是我第一次发布对我的解释和糟糕的编码感到抱歉,但希望它能帮助
我认为DT必须为null,它实际上是导致失败的for循环上方的一行