这是我的代码。我一直有错误“类型字符串的值无法转换为system.data.datatable”
Function GetTable() As DataTable
Dim SQLConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("Zeinchatconnection").ToString())
Dim CommSQL As New SqlClient.SqlCommand
Dim ChatDataAdapter As SqlDataAdapter
Dim paramSQL As SqlClient.SqlParameter
Dim DStable As DataSet
Dim table As New DataTable
Dim szName As String = ""
Dim szNumber As String = ""
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
End If
CommSQL.Connection = SQLConnection
CommSQL.CommandType = CommandType.StoredProcedure
CommSQL.CommandText = "spc_newselect"
CommSQL.ExecuteNonQuery()
ChatDataAdapter = New SqlDataAdapter(CommSQL)
ChatDataAdapter.Fill(DSTable)
table.Rows.Clear()
table.Clear()
table = DStable.Tables(0)
Dim i As Integer = 0
For i = 0 To table.Rows.Count - 1
szName = szName & " " & table.Rows(i).Item(0) & table.Rows(i).Item(1)
szNumber = szNumber & " " & table.Rows(i).Item(0) & table.Rows(i).Item(1)
Next
GetTable = "1"
Catch ex As System.Data.SqlClient.SqlException
GetTable = "0"
Catch ex As Exception
GetTable = "0"
If (IsNothing(ChatDataAdapter) = False) Then ChatDataAdapter.Dispose()
If (IsNothing(CommSQL) = False) Then CommSQL.Dispose()
SQLConnection.Close()
End Try
Return table
End Function
错误所在的部分是gettable =“1”及以下。
答案 0 :(得分:0)
您的函数GetTable
会返回DataTable
您无法将"1"
转换为DataTable
,因为消息显示行GetTable = "1"
如果您想返回DataTable
并设置标志以查看状态;改变你的函数定义:
Function GetTable(byref result as Integer) As DataTable
然后代替GetTable = "1"
将其更改为result = 1
。这样,您可以检查结果值并返回DataTable:
Dim res as Integer
Dim dt as DataTable = GetTable(res)
If res = 1 then
'It worked!
End If
旁注:启用选项严格
答案 1 :(得分:0)
GetTable = "1"
表示您要设置函数的returnValue。由于您的函数定义为Function GetTable() As DataTable
,因此编译器会显示错误!
下面几行有一个正确的返回标准(Return table
)所以我不确定你的目标是GetTable = "1"
?
我认为您希望有一个额外的returnValue来指示您的函数调用是否成功。但事实上,函数可能只有一个returnValue。
您可以选择将表格var设置为空,或使用参数参数...
' possible solution 1 - using nothing value
Function GetTable() As DataTable
Try
' your code goes here
' remove GetTable = "1"
Catch ex as Exception
' change GetTable = "0" to
table = nothing
End Try
' other code ...
End Function
' possible solution 2 - ref param
Function GetTable(ByRef status as integer) as DataTable
Try
' your code goes here
' remove GetTable = "1"
status = 1
Catch ex as Exception
' change GetTable = "0" to
status = 0
End Try
' other code ...
End Function
在解决方案2中,您还可以选择布尔参数,表示您的通话成功与否。