WPF application using DataGrid. User double-clicks on a cell, and I need to get the value of another cell in that row.
Dim dep As DependencyObject = DirectCast(e.OriginalSource, DependencyObject)
Dim dgRow As DataGridRow = Nothing
While dep IsNot Nothing
If TypeOf dep Is DataGridRow Then
dgRow = DirectCast(dep, DataGridRow)
End If
dep = VisualTreeHelper.GetParent(dep)
End While
So now, I have the row, I want to get the value from a specific column:
Dim xx As String = dgRow.Item("xx")
This gets me "Option Strict On disallows late binding" with no correction options. It works fine with Option Strict Off. I have tried all the following to correct it:
dgRow.Item("xx").ToString
DirectCast(dgRow.Item("xx"), String)
CType(dgRow.Item("xx"), String)
However, the red-squiggly line remains under dgRow.Item("xx") in all these scenarios.
Appreciate any input, including alternate ways to go about this.
UPDATE
Here's the code that ultimately worked. I looked at the type for the Item property and it was DataRowView. Thanks to Mark's answer below.
dgRow = DirectCast(DirectCast(dep, DataGridRow).Item, DataRowView)
This allowed me to do this without the late binding error:
dgRow.Item("xx").ToString
dgRow.Item
is a property of type Object
. By using dgRow.Item("xx")
you are trying to call the default property, which for Object
doesn't exist, and therefore gives you the error you are seeing.
From the ("xx")
part, it looks like the row may be bound to some sort of dictionary. If that is the case, you would need to cast dgRow.Item
to the appropriate type before accessing a value from it, e.g.
Dim xx As String = DirectCast(dgRow.Item, Dictionary(Of String, String))("xx")
UPDATE
Reading through again, it looks like you may be binding to a DataTable
, in which case each row would be bound to a DataRow
, so perhaps something like this is what you need:
Dim xx As String = DirectCast(dgRow.Item, DataRow).Field(Of String)("xx")
Note, you may need to add a reference to System.Data.DataSetExtensions.dll
for the Field
method to be available.