0

I want to delete multiple data from C# Windows form application. I used following code but not working. It shows an error. N.B: My table ID data type is Integer. Sorry i uploaded a wrong image. enter image description here

foreach (DataGridViewRow data in dataGridView1.Rows)
{
    if (bool.Parse(data.Cells[0].Value.ToString()))
    {
        conn.con.Open();
        OleDbCommand command = new OleDbCommand("Delete FROM tblTransaction WHERE ID='" + data.Cells[1].Value.ToString() + "'", conn.con);
        if (DialogResult.Yes == MessageBox.Show("Do you want to Delete this record?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
        {
        command.ExecuteNonQuery();
          MessageBox.Show("Data Deleted Successfully", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        else if (DialogResult == DialogResult.No)
        {
          //nothing to do
        }
        conn.con.Close();
    }
}
  • When you step through with the debugger, what is the value of `data.Cells[1].Value.ToString()`? – brnlmrry Feb 28 '20 at 18:58
  • 2
    Use [OleDbCommand.Parameters](https://learn.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbcommand.parameters?view=netframework-4.8) –  Feb 28 '20 at 18:58
  • i have uploaded wrong image please check error image pls. – Mithila Das Feb 28 '20 at 19:35
  • What is the stacktrace? What is the value of data.Cells[1].Value? – sam Feb 28 '20 at 19:55
  • Same thing. Using a parameterized query will solve the problem. See [this](https://stackoverflow.com/a/48996646/10216583) for example. –  Feb 28 '20 at 20:20
  • I have solved my problem sng command.Parameters.AddWithValue("@ID", data.Cells[1].Value.ToString()); But My problem is when i click delete its shows a warning yes or no dialog every time if multiple record is selected to delete. how can i solve the problem. – Mithila Das Feb 28 '20 at 20:59
  • Get rid of the `MessageBox-es` or _ask_ just before the `foreach` loop and _inform_ after the loop ends. In general, don't use a message box in a loop. –  Feb 28 '20 at 21:29

1 Answers1

0

Try something like this:

conn.con.Open();
foreach (DataGridViewRow data in dataGridView1.Rows)
{
    if (bool.Parse(data.Cells[0].Value.ToString()))
    {            
        if (DialogResult.Yes == MessageBox.Show("Do you want to Delete this record?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
        {
            OleDbCommand command = new OleDbCommand("Delete FROM tblTransaction WHERE ID='?'", conn.con);
            command.Parameters.AddWithValue("@ID", data.Cells[1].Value.ToString());
            command.ExecuteNonQuery();
            MessageBox.Show("Data Deleted Successfully", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        else if (DialogResult == DialogResult.No)
        {
          //nothing to do
        }            
    }
}
conn.con.Close();
Gonzalo Diaz
  • 139
  • 1
  • 8