我正在开发一个相对简单的 C# 项目,该项目通过 OleDb 将 Access 数据库与各种功能(例如添加、删除和编辑记录)连接起来。现在,在尝试实现数据库搜索之前,一切都运行良好。
以下行(在搜索框代码中)在调试期间引发异常,但我不确定导致它中断的实际上是什么空值。
ReturnedResults = DBDataSet.Tables["Movies"].Select("Title like '%" + Search + "%'");
所以目标是搜索数据库中的“电影”表,并根据用户的输入(存储在“搜索”字符串中)查找电影。
搜索框的代码可以在下面找到,数据库初始化和连接在底部提供。
private void SearchTextBox_Changed(object sender, EventArgs e)
{
string SearchString = SearchTextBox.Text.ToString();
int Results = 0;
DataRow[] ReturnedResults;
ReturnedResults = DataSet.Tables["Movies"].Select("Title like '%" + SearchString + "%'");
Results = ReturnedResults.Length;
if (Results > 0)
{
SearchResultsBox.Items.Clear();
for (int i = 0; i <= Results; i++)
{
DataRow Row;
Row = ReturnedResults[i];
SearchResultsBox.Items.Add(Row["Title"].ToString());
}
}
else
{
SearchResultsBox.Items.Clear();
MessageBox.Show("Error! No items found.");
}
}
对于某些上下文,这里是主数据库初始化/连接和表单加载事件:
public partial class BaseForm : Form
{
System.Data.OleDb.OleDbConnection Connection;
DataSet DataSet;
System.Data.OleDb.OleDbDataAdapter DataAdapter;
int MaxRows = 0;
int CurrentRow = 0;
public BaseForm()
{
InitializeComponent();
}
private void BaseForm_Load(object sender, EventArgs e)
{
Connection = new System.Data.OleDb.OleDbConnection();
Connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;DataSource=Movies.accdb";
Connection.Open();
DataSet = new DataSet();
string sq1 = "SELECT * From Movies";
DataAdapter = new System.Data.OleDb.OleDbDataAdapter(sq1, DBConnection);
DataAdapter.Fill(DBDataSet);
MaxRows = DataSet.Tables[0].Rows.Count;
DisplayRecord();
}