将DataGrid当前项放入对象WPF中

时间:2018-11-22 03:20:05

标签: .net wpf vb.net linq linq-to-sql

几天以来,我在将WPF DataGrid的当前项目强制转换为linq-generated实体时遇到了麻烦。如果有人可以帮助我,那将是惊人的。 我正在使用linq查询获取DataGrid的数据,如下所示:

Dim payableexpense As New exprev
Dim listofexpenses As IEnumerable(Of exprev)

Private Sub txtsearchname_TextChanged(sender As Object, e As TextChangedEventArgs) Handles txtsearchname.TextChanged
   listofexpenses = From expenses In db.exprevs
   Where expenses.school_id = currentschool.school_id AndAlso expenses.title.Contains(txtsearchname.Text.ToString) AndAlso expenses.status <> 1 AndAlso expenses.type = 1

   dgvsearchresults.ItemsSource = listofexpenses
   dgvsearchresults.Items.Refresh()
   stpexpensedetails.DataContext = payableexpense
End Sub

对于DataGrid选择更改事件,我有以下代码:

Private Sub dgvsearchresults_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles dgvsearchresults.SelectionChanged
payableexpense = dgvsearchresults.CurrentItem
End Sub

但是在run-time期间,它引发了以下异常:

  

“无法将类型为“ ms.internal.namedobject”的对象转换为“ exprev””

在我项目的另一个地方,同样的方法也可以正常工作。

1 个答案:

答案 0 :(得分:0)

使用TryCast方法尝试将SelectedItem属性强制转换为exprev

Private Sub dgvsearchresults_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles dgvsearchresults.SelectionChanged
    Dim selectedItem As exprev = TryCast(dgvsearchresults.SelectedItem, exprev)
    If selectedItem IsNot Nothing Then
        payableexpense = selectedItem
        '...
    End If
End Sub