简体   繁体   中英

Unable to cast object of type 'System.String' to type 'System.Data.DataTable' in VB.NET

I have two data tables.

Dim DataProcedure As DataTable = mySQL.GetDBDataTableSimple("CALL FullExport();")
Dim DataAPI As DataTable = getProductList()

DataProcedure has data from my database DataAPI is pulling the same data from a server

We upload data for products that are not active anymore to the server. I am pulling a list of products into DataAPI which includes a column with active or not active.

Problem : I am trying to pull data from an API and populate it into a data table. It appears that the data is not coming back from GetRequest() function. Any advice?

在此处输入图片说明

    Public Function getProductList()
    
            If (String.IsNullOrEmpty(_API)) Then
                Throw New NullReferenceException("API")
            End If
            If (String.IsNullOrEmpty(_UserNamePassword)) Then
                Throw New NullReferenceException("UserNamePassword")
            End If
    
            Dim result_post = GetRequest(New Uri(_API & "product/Get/" & StoreID), "GET")
    
            Return result_post
    
        End Function


Public Function GetRequest(uri As Uri, method As String) As String
        Dim origResponse As HttpWebResponse
        Dim origRequest As HttpWebRequest = DirectCast(HttpWebRequest.Create(uri), HttpWebRequest)
        origRequest.Headers.Add("Authorization", "Basic " & Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(_UserNamePassword)))
        origRequest.AllowAutoRedirect = False
        origRequest.Method = method

        Try
            origRequest.Timeout = 100000
            origResponse = DirectCast(origRequest.GetResponse(), HttpWebResponse)
            Dim Stream As Stream = origResponse.GetResponseStream()
            Dim sr As New StreamReader(Stream)
            Dim str As String = sr.ReadToEnd
            Console.WriteLine(str)
            Return str
        Catch ex As WebException
            MsgBox(ex.Message)
            Return String.Empty        End Try

    End Function

It appears that the data is not coming back from GetRequest() function. Any advice?

That's not apparent. You're just getting an exception (invalidcastexception) and assuming it's because your API returns nothing. Regardless of what the API returns, it's not the cause of the error

You've declared a function that returns a string (because it returns the result of a function that returns a string) and you're trying to assign it to a variable of type datatable

Dim DataApi as DataTable = THING_HERE_NEEDS_TO_RETURN_A_DATATABLE

And you have:

    Public Function getProductList()

        'GETREQUEST RETURNS A STRING. result_post IS A STRING
        Dim result_post = GetRequest(New Uri(_API & "product/Get/" & StoreID), "GET")
        'RETURNS A STRING
        Return result_post

    End Function

    'RETURNS A STRING
    Public Function GetRequest(uri As Uri, method As String) As String

So coming back to the first line of code:

Dim DataApi as DataTable = getProductList() 'THING_HERE_NEEDS_TO_RETURN_A_DATATABLE - getProductList does not return a datatable

You're going to have to parse the result string and create a datatable and return that from getProductList

How you do that, only you can know - noone here knows anything about what the resulting string from that API actually looks like

Let's say it was a CSV for a person:

"Name,Age\r\nJohn,23"

Turning that into a datatable would involve something like:

Dim lines = csv.Split(vbCr, vbLf)
Dim dt as New DataTable
For Each header in lines(0).Split(","c)
  dt.Columns.Add(header)
Next 
For i = 1 to lines.Length - 1
  Dim bits = lines(i).Split(",")
  dt.Rows.Add(bits)
Next i

It's the most primitive way of parsing a CSV possible - using a CSV library would be much better. I just wanted to write it to outline that you need quite a lot of effort somewhere to turn a string into a datatable. Strings are used to represent so many things, usually with some standard format like CSV or XML or JSON.. But the action of converting to and from is quite involved. You can't just assign a string to a non-string variable and hope VB figures it out


If you code with Option Strict On you'll get this error much sooner; your program won't even compile because the compiler will know you're trying to make an invalid assignment. Always code with Option Strict On

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM