【问题标题】:Function which returns datatable返回数据表的函数
【发布时间】:2015-12-01 07:53:35
【问题描述】:

我有一个返回数据表的函数

  Private Function _Read() As DataTable
    Dim _cmd As New SqlCommand
    Dim _da As New SqlDataAdapter(_cmd)
    Dim _dt As New DataTable
    With _cmd
        .Connection = dbRoot
        .CommandTimeout = 0
        .CommandText = "SELECT * FROM Table "
    End With

    Try
        _da.Fill(_dt)
        Return _dt
    Catch ex As Exception
        Return Nothing
    End Try

End Function

现在我想控制是否发生错误,所以我将代码放在 Try Catch 块中。

如何从我的程序中检查是否发生异常?

我可以这样设置吗

IF _Read = nothing ?

【问题讨论】:

  • returnedDT = _Read() // If returnedDT IsNot Nothing Then...

标签: vb.net


【解决方案1】:

首先,要检查 _Read 是否没有返回任何内容,您必须在 vb.net 中使用 Is 关键字:

If _Read Is nothing Then
...
End if

但是,如果您真的想“在发生错误时获得控制”,那么您要做的第一件事就是应用适当的错误处理。永远不要捕获和忽略异常。 处理异常的一种方法是通过消息框通知用户,将其记录下来。另一种选择是在过程中不包含 Catch,以便错误向上传播。

此外,您可能希望使用 finally 块来关闭和释放资源,或者使用 using 构造。见这里:SqlCommand (Using Statement / Disposing issue)

【讨论】:

  • 如果不是什么,我该如何设置?
  • 如果 _Read 不是什么都没有,那么
【解决方案2】:

尝试以下 _Read 方法的变体。此方法返回 DataTable 作为返回类型和错误消息作为输出参数。我希望这会有所帮助。

Private Function _Read(ByRef errorMsg As String) As DataTable

    Try
        'Get data from datrabase

        'return datatable
        _Read = New Data.DataTable

        'return empty if no error occured
        errorMsg = ""

    Catch ex As Exception

        'return null data table
        _Read = Nothing

        'return error code
        errorMsg = ex.Message

    End Try

End Function

在你的代码中调用这个方法

    Dim myDataTable As Data.DataTable
    Dim myErrorMsg As String = ""

    myDataTable = _Read(myErrorMsg)

    If myErrorMsg <> "" Then
        MessageBox.Show(myErrorMsg)
    End If

【讨论】:

    猜你喜欢
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 2011-03-25
    • 2017-01-02
    相关资源
    最近更新 更多