0

这是我的代码。我一直有一个错误“字符串类型的值无法转换为 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" 及以下。

4

2 回答 2

1

GetTable = "1"表示要设置函数的 returnValue。由于您的函数被定义为Function GetTable() As DataTable您的编译器显示错误!

下面几行有一个正确的 return stmt( Return table) 所以我不太确定你的目标是GetTable = "1"什么?

我假设您希望有一个额外的 returnValue 来指示您的函数调用是否成功。但事实上,函数可能只有一个 returnValue。

您可以选择将 table var 设置为空,或使用 ref 参数 ...

' 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 中,您还可以选择一个布尔参数来指示您的呼叫是否成功。

于 2012-08-16T11:56:15.727 回答
0

您的函数GetTable返回一个DataTable

您无法转换"1"为 aDataTable正如消息所暗示的那样,这就是在线上正在发生的事情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

旁注:打开 Option Strict

于 2012-08-16T11:55:43.843 回答