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!
CodePudding user response:
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, usingFOR 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);
}
}