Wednesday, January 23, 2008

DataTable Select returning a DataTable

I needed to create a web service for an application to expose some of the data to another system.  I typically like to return DataTables from web service calls for the flexibility you get.  I had some existing data layer code that I wanted to reuse for this web service, but I needed to enhance the code slightly to allow the caller to filter the data before it is returned – a typical WHERE clause.  Rather than modify the working production code, I decided to just add a bit of logic in the web service code behind page, but was having trouble getting the DataTable.Select() to return a DataTable.  I ended up being able to do it using the DataTable.Clone() method:

 

    Public Function GetComponentList(ByVal componentTypes As String) As System.Data.DataTable

        Dim x, y As DataTable

        x = ComponentManager.RetrieveAllComponents()

 

        If componentTypes <> "" Then

 

            y = x.Clone()

 

            For Each row As DataRow In x.Select("Type IN(" & componentTypes & ")")

 

                y.ImportRow(row)

            Next

            If y.Rows.Count > 0 Then

                x = y

            End If

        End If

        x.TableName = "ComponentList"

 

        Return x

    End Function

 

1 comment:

Anonymous said...

Cooooool ! Thanks !