Linus Gingerbread
Linus Gingerbread

Reputation: 11

Deleting data from OleDB C#

The columns that I have in my DB are [CusName], [CusNo], [CusAdvance], [TotalAmount], [ID] and [CusItem]. I get the input of the name of the Customer to be deleted from textBox4.Text. I have modified the code as per what I got from you guys. But still the entries are not being deleted. They still remain inside the DB.

My Code:

void Button1Click(object sender, EventArgs e)
{
   try
   {
      OleDbConnection delConn = new 
          OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data 
          Source=C:/NavneethCollection.accdb;Persist Security Info=False;");
      delConn.Open();
      String delQuery = "DELETE FROM NavColl WHERE [CusName]= @CustName";
      OleDbCommand delcmd = new OleDbCommand();
      delcmd.CommandText = delQuery;
      delcmd.Connection = delConn;
      delcmd.Parameters.AddWithValue("@CustName", textBox4.Text);
      delcmd.ExecuteNonQuery();
      MessageBox.Show("Customer has been successfully removed!");
   }
   catch(Exception exc)
   {
      MessageBox.Show("Error: "+exc.Message);
   }
}

Upvotes: 1

Views: 8165

Answers (3)

Aprendendo
Aprendendo

Reputation: 1

You can't delete rows in Excel with OleDb. You can insert and update rows, but deleting is not allowed. If your application is not running on a server, you could always use Excel interop to delete the row, but not through OleDb.

Upvotes: 0

Hadi
Hadi

Reputation: 37313

Try the following code

you have to pasa ? as parameter name instead of [CusName]

  String delQuery = "DELETE FROM NavColl WHERE [CusName]= ?";
  OleDbCommand delcmd = new OleDbCommand();
  delcmd.CommandText = delQuery;
  delcmd.Connection = delConn;
  delcmd.Parameters.AddWithValue("?", textBox4.Text);
  delcmd.ExecuteNonQuery();

Upvotes: 0

Coskun Ozogul
Coskun Ozogul

Reputation: 2469

In your delete command you should use only

try
 {
  OleDbConnection delConn = new 
      OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data 
      Source=C:/NavneethCollection.accdb;Persist Security Info=False;");
  delConn.Open();
  String delQuery = "DELETE FROM NavColl WHERE [CusName]= @CustName";
  OleDbCommand delcmd = new OleDbCommand();
  delcmd.CommandText = delQuery;
  delcmd.Connection = delConn;
  delcmd.Parameters.AddWithValue("@CustName", textBox4.Text);
  delcmd.ExecuteNonQuery();
  MessageBox.Show("Customer has been successfully removed!");
 }
 catch(Exception exc)
 {
  MessageBox.Show("Error: "+exc.Message);
 }

Upvotes: 4

Related Questions