2011-09-04 71 views
0

我有一个WPF C#datagrid,可以使用SqlDataAdapter进行过滤并使用ItemsSource属性进行显示。在过滤后编辑wpf datagrid行

我也可以在过滤之前更新/删除行,但不能之后。

diamedbEntities objContext; 
Sender objSendToEdit; 

private void Window_Loaded(object sender, RoutedEventArgs e) 
{ 
    objContext = new diamedbEntities(); 
    dgEmp.ItemsSource = objContext.Senders; 
} 

private void dgEmp_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{  
    objSendToEdit = dgEmp.SelectedItem as Sender; 
} 

private void btnDelete_Click(object sender, RoutedEventArgs e) 
{ 
    if (objSendToEdit == null) 
    { 
     MessageBox.Show("Cannot delete the blank Entry"); 
    } 
    else 
    { 
     objContext.DeleteObject(objSendToEdit); 
     objContext.SaveChanges(); 
     MessageBox.Show("Record Deleted.."); 
    } 
} 

过滤后objSendToEdit为空。 我该如何解决这个问题?

+0

应该看看CollectionViewSource,它使过滤变得简单。我在我的网站上有一个例子:http://www.jarloo.com/excel-like-autofilter-in-wpf/ – Kelly

回答

0

http://msdn.microsoft.com/en-us/library/cscsdfbt(v=VS.100).aspx

的作为操作者 就像是一个铸造操作。但是,如果转换不是 可能,则返回null而不是引发异常。

你想用objSendToEdit = dgEmp.SelectedItem as Sender;做什么?

+0

objContext.DeleteObject(objSendToEdit); objContext.SaveChanges(); – user626873

+0

好吧,让我换句话说,为什么要将'SelectedItem'投射到'Sender'类型? – CodeCaster

+0

发件人是填充datagrid的数据库表。在过滤数据网格之前,它工作正常。 – user626873

0

这是因为过滤器必须清除选择,从而使objSendToEdit为空。

您应该在过滤后立即重新选择objSendToEdit回到数据网格。

objSendToEdit = dgEmp.SelectedItem; 
    //// filter code 
    dgEmp.SelectedItem = objSendToEdit; 

让我知道这是否有帮助。