为什么我的活动会运行两次?

时间:2014-03-31 09:23:04

标签: asp.net vb.net

我有一个按钮

 <asp:Button ID="Button1" runat="server" Text="Button"  onclick="Button1_Click" UseSubmitBehavior="False" />

我的活动是

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("Document_RecordConnectionString1").ToString())
        con.Open()
        Dim del As New SqlCommand(" delete from TableA where RefNo = '" & Request.QueryString("RefNo") & "'", con)
        del.ExecuteNonQuery()
        For i As Integer = 0 To displayCBL.Items.Count - 1

            If displayCBL.Items(i).Selected Then
                Dim cmd As New SqlCommand("Insert into TableA (RefNo,Text,InsertDate) values('" & Request.QueryString("RefNo") & "','" & displayCBL.Items(i).Value & "',getdate())", con)
                cmd.ExecuteNonQuery()

            End If
        Next
        con.Close()
End Sub

我注意到我的子例程运行了两次,因此插入数据两次(调试器和SQL Server分析器都确认了这一点)。有什么我想念的吗?

1 个答案:

答案 0 :(得分:8)

答案很简单。上面的代码将事件称为TWICE。让onclick="Button1_Click"Handles Button1.Click都出错。选择其中一个就足够了。

您可以阅读更多内容:

OnClick and Handles Caution: Events Firing Twice

ASP.Net OnClick vs Function() Handles buttonName.Click