I am trying to execute a query to delete a book record from my database given an ID. When I click the delete button, I get the following error:
ExecuteNonQuery: Connection property has not been initialized.
My code so far is:
private void btnDelete_Click(object sender, EventArgs e)//delete book
{
SqlCommand com = new SqlCommand("DELETE FROM [tbl_Book] WHERE Book_ID='"+txtBookID.Text+"'");
cn.Open();
com.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Book Deleted Successfully", "System", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
You have to initialize new sql connection
and pass it to Sql command object
.
private void btnDelete_Click(object sender, EventArgs e)
{
Sqlconection connection = new Sqlconection("Your Connection String Here");
connection.Open();
SqlCommand com = new SqlCommand("DELETE FROM [tbl_Book] WHERE Book_ID='"+txtBookID.Text+"'", connection);
com.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Book Deleted Successfully", "System", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Hopes this helps...
You did not bind the command with connection
. You can do it right in constructor.
SqlCommand com = new SqlCommand("Your Query", connection);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.