vb.net 返回数据表的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34015247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Function which returns datatable
提问by myString
I have a function which returns datatable
我有一个返回数据表的函数
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
Now i want to get control if error ocurs so i put the code inside the Try Catch block.
现在我想控制是否发生错误,所以我将代码放在 Try Catch 块中。
How can i check from my program did exception happend ?
我如何从我的程序中检查是否发生了异常?
Can i set like this
我可以这样设置吗
IF _Read = nothing ?
回答by chrisl08
First, to check if _Read returned nothing, you have to use the Is keyword in vb.net :
首先,要检查 _Read 是否没有返回任何内容,您必须在 vb.net 中使用 Is 关键字:
If _Read Is nothing Then
...
End if
But If you really want to "get control if error occurs" then the first thing you have to do is apply proper error handling. Never catch and ignore exceptions. A way to handle the exception is to notify the user through a message box, log it. Another option is not to have a Catch in the procedure so that the error is propagated up the stack.
但是,如果您真的想“在发生错误时获得控制权”,那么您要做的第一件事就是应用正确的错误处理。永远不要捕捉和忽略异常。处理异常的一种方法是通过消息框通知用户,将其记录下来。另一种选择是在过程中不使用 Catch,以便错误沿堆栈向上传播。
Also, you may want to have a finally block to close and release resources, or use a using construct. See here : SqlCommand (Using Statement / Disposing issue)
此外,您可能希望使用 finally 块来关闭和释放资源,或使用 using 构造。请参阅此处:SqlCommand(使用语句/处理问题)
回答by Muhammad Irfan Azam
Try below variation of _Read method. This method returns DataTable as return type and error message as output parameter. I hope this will help.
尝试以下 _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
Call this method in you code as
在您的代码中调用此方法为
Dim myDataTable As Data.DataTable
Dim myErrorMsg As String = ""
myDataTable = _Read(myErrorMsg)
If myErrorMsg <> "" Then
MessageBox.Show(myErrorMsg)
End If

