0

I have used Entity Framework to create a local database. Now I've created a form where I can add a person to a listbox and it also adds to the database. How do I remove the selected item from the listbox tho whilst also being removed from the database?

The person is an object so I feel like I have to do something in the lines of:

Person person = new Person();
var removeperson = new Person{

 " for loop for removing selected index"

}

Person.Remove(removeperson);

Something like that. I have a remove method in the Person class but I just dont know how to use it whilst also removing it from the list.

I'm pretty new at C# so please let me know if I haven't given enough information for y'all to help me.

2
  • 1
    Try [your db context].SaveChanges() Oct 21, 2015 at 12:50
  • I've already used SaveChanges() to save all changes done when adding and removing, they're in classes already.
    – schivv
    Oct 21, 2015 at 12:51

2 Answers 2

0

After a bit of looking around there seems to be two methods to go about this, first would be as Volkan said and the second seems to be taking the value of the selected field and passing it in to a query which deletes it from the database. Then you can remove it from the list and both areas will be rid of that entry.

0

Try like this:

for(int i=0; i < listBox1.SelectedItems.Count; i++) 
{
   listBox1.Items.Remove(listBox1.SelectedItems[i]);
   OleDbCommand cmd = new OleDbCommand("DELETE FROM myatble WHERE item = " + listBox1.SelectedItem + "", GetConnection());
   cmd.ExecuteNonQuery()
}
4
  • Please do not delete each item from the database one by one, you should keep an identifier in a list and delete them all together. (:
    – Jannik
    Oct 21, 2015 at 13:02
  • 1
    @Jannik:- Indeed, infact that should be the idle approach. But this just came to my mind :) Oct 21, 2015 at 13:03
  • It's for a school project where the database gets created everytime I start the program. I then add a Person to a list and it also adds to the database. Later I want to select one of the persons I've created and put in the list by selecting it and removing it so it removes from the list but also the database.
    – schivv
    Oct 21, 2015 at 13:05
  • We also have predefined methods like a Remove method that will do all the queries for me so that wont be a problem. It should only be something easy as using the remove method from the Person-class by using Person.Remove(item); but I dont' know how to do this on the selected item from the listbox.
    – schivv
    Oct 21, 2015 at 13:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.