嘿,我意识到这个问题之前已经被问过,但即使我按照答案,我似乎仍然无法让我的代码工作。错误发生在“data_adapter.Fill(temp_table)” 任何有关正在发生的事情的帮助将不胜感激。
string ConnStr = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = H:\\School Work\\Computing A Level\\Stock checker\\Program\\Morgan's Motors Database.mdb";
string Query = "SELECT * FROM [Car Info] WHERE @x ";
string FirstQuery = null;
int i = 0;
for (i = 0; i < ColumnName.Count - 1; i++)
{
FirstQuery += string.Format("{0} = {1} AND ", ColumnName[i], EnteredFields[i]);
}
FirstQuery += string.Format("{0} = {1}", ColumnName[i], EnteredFields[i]);
MessageBox.Show(Query);
OleDbConnection database_connection = new OleDbConnection(ConnStr);
OleDbCommand database_command = new OleDbCommand(Query, database_connection);
database_command.Parameters.AddWithValue("@x", FirstQuery);
OleDbDataAdapter database_adapter = new OleDbDataAdapter();
database_adapter.SelectCommand = new OleDbCommand(database_command.CommandText, database_connection);
DataTable temp_table = new DataTable();
database_adapter.Fill(temp_table);
BindingSource data_source = new BindingSource();
data_source.DataSource = temp_table;
dataGridView1.DataSource = data_source;
编辑:我在重构代码方面取得了一些进展,现在的问题是“?” 没有被替换
string ConnStr = "Provider = Microsoft.ACE.OLEDB.12.0; 数据源 = H:\School Work\Computing A Level\Stock checker\Program\Morgan's Motors Database.mdb;";
OleDbConnection conn_database = new OleDbConnection();
conn_database.ConnectionString = ConnStr;
OleDbCommand comm_database = new OleDbCommand();
comm_database.CommandText = "SELECT * FROM [Car Info] WHERE ? = ?";
comm_database.Connection = conn_database;
OleDbDataAdapter adap_database = new OleDbDataAdapter(comm_database);
DataTable data_database = new DataTable();
for (int i = 0; i < ColumnName.Count; i++)
{
comm_database.Parameters.AddWithValue("?", ColumnName[i].ToString());
comm_database.Parameters.AddWithValue("?", EnteredFields[i].ToString());
MessageBox.Show(adap_database.SelectCommand.CommandText);
adap_database.Fill(data_database);
}
BindingSource bind_database = new BindingSource();
bind_database.DataSource = data_database;
dataGridView1.DataSource = bind_database;