I am attempting to add items to an Access database in C#. I have code that seems to work (I can open and close a database), but the button click event produces errors. I have been searching on Google for the whole afternoon but no joy. My code is:
private void button26_Click(object sender, EventArgs e)
{ //Setup tab LoadDatabase
try
{
connection.Open();
button26.ForeColor = Color.Lime;
mainDataGridView.Visible = true;
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "INSERT INTO Main('Prop', 'Value', 'Default','Type') VALUES('one', 'Kelly', 'Jill','one')";
cmd.ExecuteNonQuery();
button26.Text = "Done Insert";
connection.Close();
}
catch (Exception ex)
{
richTextBox1.Text=("Error "+ex);
button26.ForeColor = Color.Black;
connection.Close();
}
}
And the error I get is:
Error System.InvalidOperationException: ExecuteNonQuery: Connection property has not been initialized.
at System.Data.OleDb.OleDbCommand.ValidateConnection(String method)
at System.Data.OleDb.OleDbCommand.ValidateConnectionAndTransaction(String method)
? at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at CrewCheifSettingsBeta3.Form1.button26_Click(Object sender, EventArgs e) in C:\Somepath\Form1.cs:line 49
Clearly something wrong with the connection string, and that it's not SQL-injection proof either.