简体   繁体   中英

Delete Items from ListView and List in C#

I worked out how to delete an item from my listview with this code:

private void buttonDelete_Click(object sender, EventArgs e) {
    if (listViewStudents.SelectedItems != null) {
        foreach (ListViewItem eachItem in listViewStudents.SelectedItems) { 
            listViewStudents.Items.Remove(eachItem);
            ClearandFocus();
        }
    }
}

But as you can see in the code below every time input gets added into the ListView it also gets added into a collection list with Repository.AddStudent(student)

private void buttonAdd_Click(object sender, EventArgs e) {
     Student student = GetStudent();
     Repository.AddStudent(student);
     string[] row = { student.LastName, student.StreetAddress, student.StreetNumber, student.Box, student.Zip, student.City,
                      student.Country, student.Birthday, student.Birthplace, student.Gender, student.IDNumber, student.MaritalStatus };
     listViewStudents.Items.Add(student.FirstName.ToString()).SubItems.AddRange(row);
     ClearandFocus();
 }

What I would like to achieve is as following: every time the delete button gets clicked I would like to have the selected item deleted in the listview AND the list. I've done serveral attempts but can't seem to get this done, I wonder if this is even possible?

Synchronizing two lists is not trivial and doing so amually is not recommended.

Consider making your list of Students an ObservableCollection<> and set it as the ItemsSource of your ListView . Changes in the collection will be reflected in you ListView then.

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