我有以下子程序:
Private Sub Exceptionquery()
Dim connection As System.Data.SqlClient.SqlConnection
Dim connectionString As String = "Initial Catalog=mdr;Data Source=xxxxx;uid=xxxxx;password=xxxxx"
Dim _sql As String = "SELECT [Exceptions].Employeenumber,[Exceptions].exceptiondate, [Exceptions].starttime, [exceptions].endtime, [Exceptions].code, datediff(minute, starttime, endtime) as duration INTO scratchpad3 " + _
"FROM [Exceptions]" + _
"where [Exceptions].exceptiondate between @payperiodstartdate and payperiodenddate" + _
"GROUP BY [Exceptions].Employeenumber, [Exceptions].Exceptiondate, [Exceptions].starttime, [exceptions].endtime," + _
"[Exceptions].code, [Exceptions].exceptiondate"
connection = New SqlConnection(connectionString)
connection.Open()
Dim _CMD As SqlCommand = New SqlCommand(_sql, connection)
_CMD.Parameters.AddWithValue("@payperiodstartdate", payperiodstartdate)
_CMD.Parameters.AddWithValue("@payperiodenddate", payperiodenddate)
connection.Close()
End Sub
Public Sub exceptionsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exceptionsButton.Click
Exceptionquery()
Dim connection As System.Data.SqlClient.SqlConnection
Dim adapter As System.Data.SqlClient.SqlDataAdapter = New System.Data.SqlClient.SqlDataAdapter
Dim connectionString As String = "Initial Catalog=mdr;Data Source=xxxxx;uid=xxxxx;password=xxxxx"
Dim ds As New DataSet
Dim _sql As String = "SELECT * from scratchpad3"
connection = New SqlConnection(connectionString)
connection.Open()
Dim _CMD As SqlCommand = New SqlCommand(_sql, connection)
_CMD.Parameters.AddWithValue("@payperiodstartdate", payperiodstartdate)
_CMD.Parameters.AddWithValue("@payperiodenddate", payperiodenddate)
adapter.SelectCommand = _CMD
Try
adapter.Fill(ds)
If ds Is Nothing OrElse ds.Tables.Count = 0 OrElse ds.Tables(0).Rows.Count = 0 Then
'it's empty
MessageBox.Show("There was no data for this time period. Press Ok to continue", "No Data")
connection.Close()
Exceptions.saveButton.Enabled = False
Exceptions.Show()
Else
connection.Close()
Exceptions.Show()
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
connection.Close()
End Try
End Sub
当我按下按钮时:
Public Sub exceptionsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exceptionsButton.Click
我的子程序Exceptionquery
没有被解雇。我知道这可能是一件很简单的事情,但我不知道它是什么。有人可以帮我解决这个问题吗?
谢谢
答案 0 :(得分:0)
你确定ExceptionQuery()是从exceptionsButton_Click运行的吗?您显示的示例应该有效。单步执行调试器并验证您的按钮事件是否实际触发。
答案 1 :(得分:0)
它应该工作,检查是否完全调用了事件处理程序exceptionsButton_Click,如果执行进入它,则查看断点。
P.S。 一个非常重要的小细节:您处理连接的方式不是最佳的,您可以使用using块,如下所示:
using (dim connection as New SqlConnection(connectionString)
...
通过这种方式,你确定连接已经关闭并在耗尽范围时被处理掉,并且你不需要if / else和catch中的所有那些connection.close,无论如何你到目前为止都是错误的,因为如果连接已关闭,您进入捕获并尝试再次关闭它,将出现另一个错误。