【问题标题】:Delete Items from ListView and List in C#从 C# 中的 ListView 和 List 中删除项目
【发布时间】:2015-12-07 14:30:15
【问题描述】:

我想出了如何使用以下代码从我的列表视图中删除一个项目:

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

但是正如您在下面的代码中看到的,每次输入被添加到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();
 }

我想要实现如下:每次单击删除按钮时,我都希望在列表视图和列表中删除所选项目。我做了几次尝试,但似乎无法完成,我想知道这是否可能?

【问题讨论】:

  • 您可以考虑使用 ObjectListView (objectlistview.sourceforge.net/cs/index.html),它的工作方式是为它提供要显示的对象列表,然后您操作此对象列表,listview 会相应地更新。这样您就不需要为 ListView 单独列出对象。
  • 你应该看看 MVVM 和数据绑定。具体来说,您将创建一个视图模型,其中包含列表的公共属性、删除按钮的命令和添加按钮的命令。然后将命令绑定到列表到 ListView 的相应按钮。

标签: c# list listview


【解决方案1】:

同步两个列表并非易事,不建议这样做。

考虑将学生列表设为ObservableCollection<>,并将其设置为ListViewItemsSource。集合中的更改将反映在您ListView 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    相关资源
    最近更新 更多