我使用此代码尝试使应用程序过滤文本框中的文本,但它拒绝这样做并且错误消息不断弹出。这是代码:
using System.Windows.Forms;
using System.Configuration;
using System.Data.OleDb;
namespace TestBarcode
{
public partial class StaffHome : Form
{
private OleDbConnection connection = new OleDbConnection();
public StaffHome()
{
InitializeComponent();
connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Projects\POS\Database\MainDatabase_POS.accdb;Persist Security Info=False;";
}
private void StaffHome_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from InventoryManagement";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
try
{
connection = new OleDbConnection();
connection.Open();
OleDbCommand command = new OleDbCommand("Select * from InventoryManagement where ID like '" + textBox1.Text + "%'", connection);
OleDbDataAdapter adp = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
adp.Fill(dt);
dataGridView1.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show("Error" + ex);
}
有没有办法让这种情况发生?如果是这样,请帮助。感谢。
编辑:这是错误消息的图像。 Error msg Box
答案 0 :(得分:0)
第二个命令在OleDbConnection变量上调用NEW。结果是,这会重新创建OleDbConnection,但会错过所需连接字符串的初始化
在此上下文中,您仍应使用全局对象,而不是创建新连接。 所以只需删除此行
// This creates a new OleDbConnection without the connection string
connection = new OleDbConnection();
但是我不喜欢使用全局对象进行连接。连接内部使用非常规资源,这些资源在异常情况下很难正确处理,并且始终最好创建本地连接并仅保留全局连接字符串。此模式允许引入using语句,该语句正确销毁连接并释放连接保留的非托管资源