Search code examples
asp.netvb.netdataviewidatareader

Unable to cast object of type 'System.Data.DataView' to type 'System.Data.IDataReader'


I have a function (on vb.net) to get a data from a XMLWebService:

Private Function GetDataSchedule() As DataTable
    Dim xTable As Data.DataTable
    xTable = xMaster.GetSchedule()

    'Bind to DataTable
    Dim DT As New System.Data.DataTable
    DT.Load(xTable.DefaultView) '--> When I set a breakpoint, the error start from here

    Return DT
End Function

And then the function to call the GetDataSchedule() Function:

Public Sub ShowDataSchedule()
    Dim DSSchedule As New System.Data.DataSet
    DSSchedule.Tables.Add(GetDataSchedule) 

End Sub

But then when I executed the code, it results on get the error message: Unable to cast object of type 'System.Data.DataView' to type 'System.Data.IDataReader'.

When I just execute the GetDataSchedule() Function, it return value, but when I make it separately to call the function, then it got error. Am I missing something? Need your help. Thanks...


Solution

  • Try this

    DSSchedule.Tables.Add(GetDataSchedule().Copy())
    

    Although, since you might get back a null reference from GetDataSchedule(), it would be better to re factor your code a bit:

    Dim schedule as Data.DataTable = GetDataSechedule()
    If Not IsNothing(schedule) Then
        DSSchedule.Tables.Add(schedule.Copy())
    End If
    

    Otherwise, your code will go boom if you try to perform a .Copy() on a null reference.