![](/img/trans.png)
[英]asp.net Unable to cast object of type 'System.String' to type 'System.Data.DataTable' Using VB
[英]Unable to cast object of type 'System.String' to type 'System.Data.DataTable' in VB.NET
我有两个数据表。
Dim DataProcedure As DataTable = mySQL.GetDBDataTableSimple("CALL FullExport();")
Dim DataAPI As DataTable = getProductList()
DataProcedure 有来自我的数据库的数据 DataAPI 正在从服务器提取相同的数据
我们将不再活跃的产品的数据上传到服务器。 我将产品列表拉入 DataAPI,其中包括一个带有活动或不活动的列。
问题:我试图从 API 中提取数据并将其填充到数据表中。 数据似乎没有从 GetRequest() 函数返回。 有什么建议吗?
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
数据似乎没有从 GetRequest() 函数返回。 有什么建议吗?
这不明显。 您只是收到一个异常 (invalidcastexception) 并假设这是因为您的 API 没有返回任何内容。 无论API返回什么,都不是错误的原因
您已经声明了一个返回字符串的函数(因为它返回一个返回字符串的函数的结果)并且您正试图将其分配给数据表类型的变量
Dim DataApi as DataTable = THING_HERE_NEEDS_TO_RETURN_A_DATATABLE
你有:
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
所以回到第一行代码:
Dim DataApi as DataTable = getProductList() 'THING_HERE_NEEDS_TO_RETURN_A_DATATABLE - getProductList does not return a datatable
您将不得不解析结果字符串并创建一个数据表并从getProductList
返回它
你是怎么做到的,只有你自己知道——这里没有人知道那个 API 的结果字符串实际上是什么样子的
假设这是一个人的 CSV:
"Name,Age\r\nJohn,23"
将其转换为数据表将涉及以下内容:
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
这是解析 CSV 的最原始方法 - 使用 CSV 库会更好。 我只是想写它来概述您需要在某处付出很多努力才能将字符串转换为数据表。 字符串用于表示很多东西,通常使用一些标准格式,如 CSV 或 XML 或 JSON。但转换和转换的动作相当复杂。 你不能只是将一个字符串分配给一个非字符串变量并希望 VB 解决它
如果您使用Option Strict On
编码,您将很快收到此错误; 您的程序甚至无法编译,因为编译器会知道您正在尝试进行无效分配。 始终使用 Option Strict On 进行编码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.