Nawoda Wijebandara
Nawoda Wijebandara

Reputation: 15

How to delete an selected item from listbox same time removing from database?

enter image description here

private void button5_Click(object sender, EventArgs e)
{
  cn.Open();
  SqlCommand cmd = new SqlCommand("DELETE FROM data WHERE item ='" + listBox1.SelectedItem + "'", cn);
  cmd.ExecuteNonQuery();
  cn.Close();  
}

When I run the programme and click the remove button, It is working. But When running if I input some data into database and try to delete it, give this error

Upvotes: 1

Views: 303

Answers (1)

DreamTeK
DreamTeK

Reputation: 34177

As your code does not directly identify the issue I will have to make an assumption. I believe that somewhere in your call a previous connection has not been closed and therefore cannot be opened again.

I strongly recommend that you replace your sql request with using statements to ensure efficient closing of all connection and to also dispose of the connection when complete.

If you do this thoughout your application this type of error will not happen.

using (SqlConnection cn = new SqlConnection(connectionString)) 
{    
  using (SqlCommand cmd = new SqlCommand("DELETE FROM data WHERE item ='" +  listBox1.SelectedItem + "'", cn);
  {
    cn.Open();
    cmd.ExecuteNonQuery();
  }
}

Upvotes: 1

Related Questions