Search code examples
vb.netdatatablefinddatarowcollection

How to use TypedDataTable.Rows.Find(key as object) to find a row which has a composite key?


I have a TypedDataTable called CamerasDT which has a composite Primary Key of GroupId and CameraId. I want to use TypedDataTable.Rows.Find(key as object) to return a specific row by GroupId and CameraId. I don't seem to be able to find a way to send primary key to the find function. Any help is appreciated.


Solution

  • Use the one of the overloads for the Find method to pass an array of Objects that corresponds to the primary key values you're searching for.

    Example from the MSDN article I linked:

    The following example uses the values of an array to find a specific row in a collection of DataRow objects. The method assumes that a DataTable exists with three primary key columns. After creating an array of the values, the code uses the Find method with the array to get the particular object that you want.

     Private Sub FindInMultiPKey(ByVal table As DataTable)
        ' Create an array for the key values to find.
        Dim findTheseVals(2) As Object
    
        ' Set the values of the keys to find.
        findTheseVals(0) = "John"
        findTheseVals(1) = "Smith"
        findTheseVals(2) = "5 Main St."
    
        Dim foundRow As DataRow = table.Rows.Find(findTheseVals)
        ' Display column 1 of the found row.
        If Not (foundRow Is Nothing) Then
            Console.WriteLine(foundRow(1).ToString())
        End If
    End Sub
    

    In your case you'd pass an Object array with values to search for in your GroupId and CameraId fields.