I am creating a delete button for a project I am working on, but when I try to delete the selected value from a database it gives me an error of index out of range. And the value return is -1.
The code below is what I am working on:
private void btnDeleteBook_Click(object sender, EventArgs e){
string sql;
if (lstBooks.SelectedIndex == -1)
{
ShowMessage("Please select a item to delete.");
return;
}
clsBooks tempRecord = (clsBooks)mBooks[lstBooks.SelectedIndex - 2];
int id = tempRecord.BookID;
if (MessageBox.Show("Please review the record details and click OK to confirm your delete request.", "Confirm Delete", MessageBoxButtons.OKCancel) !=
DialogResult.OK)
{
ShowMessage("Delete request cancled.");
return;
}
sql = "DELETE FROM EBOOK WHERE BookID = " + clsSQL.ToSql(id) + ";";
try
{
openDatabaseConnection();
mDB.Open();
OleDbCommand cmd;
cmd = new OleDbCommand(sql, mDB);
cmd.ExecuteNonQuery();
ShowMessage("The record has been deleted from the Ebook Table.");
}
catch (Exception ex)
{
ShowMessage("There was an unexpected problem deleting the records: " + ex.Message);
}
finally
{
closeDatabaseConnection();
}
LoadDBTable("SELECT * FROM EBOOK Order BY BookID;");
showBooks();
}