今天研究了下在DataGrid中选中多行数据并删除的实现,用了些笨方法,还请高手指教
MainWindow
1 public partial class MainWindow : Window
2 {
3 public ObservableCollection<Albums> obserAll = new ObservableCollection<Albums>();
4 private IQueryable<Albums> iquerAll = Class1.allList();
5 public MainWindow()
6 {
7 InitializeComponent();
8 //将查询所得数据放入ObservableCollection类型的集合里
9 foreach (var a in Class1.allList())
10 {
11 obserAll.Add(a);
12 }
13 //将ObservableCollection类型的集合值绑定里DataGrid上,以现实数据表显示的实时更新
14 dataGrid1.DataContext = obserAll;
15 }
16
17 //删除操作
18 private void button1_Click(object sender, RoutedEventArgs e)
19 {
20 List<Albums> temp = new List<Albums>();//将要删除了的数据放入一个临时集合
21 foreach (Albums a in dataGrid1.SelectedItems)
22 {
23 Class1.delA(a);
24 temp.Add(a);
25 }
26 //利用临时集合来更新用于显示的ObservableCollection类型集合,使之与数据库同步
27 foreach (Albums a in temp)
28 {
29 obserAll.Remove(a);
30 }
31
32 }
33 }
Linq删除操作:
1 public static class Class1
2 {
3 private static DataClasses1DataContext db = new DataClasses1DataContext();
4 public static void delA(Albums album)
5 {
6 db.Carts.DeleteAllOnSubmit(album.Carts);
7 db.Albums.DeleteOnSubmit(album);
8 db.SubmitChanges();
9 }
10
11 }