I’m working on a relatively straight forward C# project that connects an Access Database via OleDb with various functions such as adding, deleting and editing records. Now, everything has worked fine up until trying to implement a database search.
The following line (in the searchbox code) throws up the exception during debug, but I am unsure what is actually a null value that is causing it to break.
ReturnedResults = DBDataSet.Tables["Movies"].Select("Title like '%" + Search + "%'");
So the goal is to search through the ‘Movies’ table in the database and find movies based on the user’s input (stored in the ‘Search’ string).
The search box’s code can be found below, and the database initialisation and connection is provided at the bottom.
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.");
}
}
For some context here is the main database initialisation/connection and the form load events:
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();
}
Multiple things can be null in your statement. DBDataSet can be null, or the table
Moviesdoesn’t exits. You may add following check before the line.You may also try accessing the record against
Tables[0]instead of TableMoviesEDIT:
For your next problem, mentioned in the comment, your for loop is executing till the length. It should be like:
You need to modify the condition and remember the index starts from 0 and you will get rows till
Result - 1