简体   繁体   中英

SQL connection selecting row to delete

I've got a local db in visual studio and in my project i want to delete a row wich is selected in the WPF.

This is what i've got so far:

   private void Delete(object sender, RoutedEventArgs e)
    {
        DataRowView o = (DataRowView)g2.SelectedItem;
        int ID = Convert.ToInt32(o.Row.ItemArray[0]);
        
        SqlConnection con = new SqlConnection();
        con.ConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=MYFOLDER";    
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd = new SqlCommand("DELETE FROM [STOCK] WHERE o = @ID", con);
         
        cmd.Connection = con;
        cmd.ExecuteNonQuery();
        {
            MessageBox.Show("Row deleted");  
        }

In this statement i can select a row:

DataRowView o = (DataRowView)g2.SelectedItem; int ID = Convert.ToInt32(o.Row.ItemArray[0]);

But then i have to delete it from my local db and i don't know how to complete this. I know this statement is wrong...but what is the right one: cmd = new SqlCommand("DELETE FROM [STOCK] WHERE o = @ID", con);

Hope anybody can help me. I'm using visual studio 2019 - it's a WPF project with C#.

Greetings!

You would need to refer to the ID column in your DELETE

Note also the following

  • AttachDbFilename is a bad idea , instead attach the database normally, using FOR ATTACH
  • Don't hard-code the connection string, put it in a settings file
  • You need to add the parameter to the command
  • You should always dispose the connection and command etc objects with using
  • Do not block the thread with a message box while the connection is open
  • Handle errors with a try catch
private void Delete(object sender, RoutedEventArgs e)
{
    DataRowView o = (DataRowView)g2.SelectedItem;
    int ID = Convert.ToInt32(o.Row.ItemArray[0]);

    try
    {        
        const string query = @"
DELETE FROM [STOCK] WHERE [STOCK].Id = @ID;
";
        using (SqlConnection con = new SqlConnection(Properties.ConnectionString))
        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            cmd.Parameters.Add("@ID", SqlDbType.Int).Value = ID;
            con.Open();
            cmd.ExecuteNonQuery();
        }
        MessageBox.Show("Row deleted");
    }
    catch(Exception ex)
    {
        MessageBox.Show("Error occurred:\r\n" + ex.Message);
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM