Peca
Peca

Reputation: 23

c# deleting whole row in access database

I have question about my problem. Thru manustrip in form1 i have made new form2 when i click on a right option. This form is for deleting data in access database if you pick in combobox ID of row it deletes the whole row wher is ID 4 or somethig else... My combobox is connected on my database. my code:

public partial class Form2 : Form
{
    public string myConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Bojan\Desktop\Programiranje\School\Novo\Novo\Ure.accdb";  // to je provider za Access 2007 in več - če ga ni na lokalni mašini ga je treba namestiti!!!

    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'dataSet1.Ure' table. You can move, or remove it, as needed.
        this.ureTableAdapter.Fill(this.dataSet1.Ure);
    }

    private void Brisanje_Click(object sender, EventArgs e)
    {
        OleDbConnection myConnection = null;

        myConnection = new OleDbConnection();                      // kreiranje konekcije
        myConnection.ConnectionString = myConnectionString;
        myConnection.Open();

        OleDbCommand cmd = myConnection.CreateCommand();
        cmd.Connection = myConnection;
        cmd.CommandText = "DELETE FROM Ure WHERE (ID) = '"+Izbor.SelectedValue+"'";
        cmd.ExecuteNonQuery();
        cmd.Prepare();
        myConnection.Close();
    }
}

Thanks for your help

Upvotes: 0

Views: 1214

Answers (1)

JMK
JMK

Reputation: 28059

As @musefan pointed out, you should really be using parameterised queries, the other issue seems to be the single quotes around ID which will result in a data type mismatch error. Finally, your connection and command objects implement IDisposable so I would recommend wrapping them in a using block.

The following code should work

using (var myConnection = new OleDbConnection(myConnectionString))
using (var myCommand = myConnection.CreateCommand())
{
    var idParam = new OleDbParameter("@id", Izbor.SelectedValue);

    myCommand.CommandText = "DELETE FROM Ure WHERE (ID) = @id";
    myCommand.Parameters.Add(idParam);

    myConnection.Open();
    myCommand.ExecuteNonQuery();
}

Upvotes: 3

Related Questions