[英]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)
但是正如您在下面的代码中看到的那样,每次将输入添加到
ListView
它也会使用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
. 考虑将学生列表设置为
ObservableCollection<>
并将其设置为ListView
的ItemsSource
。 Changes in the collection will be reflected in you ListView
then. 然后,集合中的更改将反映在您的
ListView
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.