我想使用Access 2017在ComboBox中进行自动完成。所以我使用了这段代码...但是有一些错误,比如:
“名称'da'在当前上下文中不存在”。
请帮我解决此错误。
private void Autocomplete()
{
string query;
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/Neth1.accdb");
//opening connection
con.Open();
try
{
//initialize a new instance of sqlcommand
OleDbCommand cmd = new OleDbCommand();
//set a connection used by this instance of sqlcommand
cmd.Connection = con;
//set the sql statement to execute at the data source
cmd.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter();
//set the sql statement or stored procedure to execute at the data source
da.SelectCommand = cmd;
//initialize a new instance of DataTable
DataTable dt = new DataTable();
//add or resfresh rows in the certain range in the datatable to match those in the data source.
da.Fill(dt);
foreach (DataRow r in dt.Rows)
{
//getting all rows in the specific field|Column
var rw = r.Field<string>("IMEI");
//Set the properties of a combobox to make it auto suggest.
comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
//adding all rows into the combobox
comboBox1.AutoCompleteCustomSource.Add(rw);
}
}
catch (Exception ex)
{
//catching error
MessageBox.Show(ex.Message);
}
//release all resources used by the component
da.Dispose();
//clossing connection
con.Close();
}
答案 0 :(得分:0)
由于您使用的是try / catch块,我建议您包含con.Open()。
打开连接也可能会失败。
当您处理oledb对象时,使用它也是一种健康的做法 {using blocks},用于处理()您创建的(一次性)对象。
你不想要的是在foreach循环中设置这些控件属性 使用AddRage填充组合框AutoCompleteCustomSource也更有效,而不是每个角色添加一个对象。
这就是我建议编辑代码的方法:
//
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
//
string query = "SELECT SomeThing";
List<string> rw = new List<string>();
try
{
using (OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/Neth1.accdb"))
{
con.Open();
using (OleDbCommand oCmd = new OleDbCommand(query, con))
{
using (OleDbDataReader _reader = oCmd.ExecuteReader())
{
if (_reader.HasRows == false) { return; }
while (_reader.Read())
{
rw.Add((string)_reader["IMEI"]);
}
}
}
}
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
comboBox1.AutoCompleteCustomSource.Clear();
comboBox1.AutoCompleteCustomSource.AddRange(rw.ToArray());
rw = null;
答案 1 :(得分:0)
您的OleDbDataAdapter da = new OleDbDataAdapter();
位于try {}范围内且
da.Dispose();
超出了该范围,请尝试将此行放在try {}范围内,或将OleDbDataAdapter da = new OleDbDataAdapter();
移到try {}范围之外。