arash rajaei
arash rajaei

Reputation: 317

insert command inserts several rows in table

I'm using this code to insert in database , but every time it inserts more than one row ,what is the problem ?

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
    Dim dob As DateTime = DateTime.Parse(Request.Form(TextBox6.UniqueID))

    Dim conString As String = ConfigurationManager.ConnectionStrings("sqlexpress").ConnectionString

    Using con As New System.Data.SqlClient.SqlConnection(conString)

        Dim com As New SqlCommand("INSERT INTO main (GroupID, Name, Description, ModeUD, StartNum, StartDate, Rate) VALUES (" & TextBox1.Text & ",'" & TextBox2.Text & "','" & TextBox3.Text & "'," & Me.DropDownList1.SelectedItem.Value & "," & TextBox4.Text & ",'" & dob & "'," & TextBox5.Text & ")", con)

        con.Open()
        com.ExecuteNonQuery()
        con.Close()





    End Using
End Sub

Upvotes: 0

Views: 120

Answers (3)

arash rajaei
arash rajaei

Reputation: 317

I have checked and hole the button click was executed twice , I have changed the code to this one and it has been solved , but I dont know why the click event is executed twice :

 Dim i As Boolean = True


  Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
    Dim dob As DateTime = DateTime.Parse(Request.Form(TextBox6.UniqueID))

    Dim conString As String = ConfigurationManager.ConnectionStrings("sqlexpress").ConnectionString





    Using con As New System.Data.SqlClient.SqlConnection(conString)
        con.Open()
        Using com As New SqlCommand("INSERT INTO main (GroupID, Name, Description, ModeUD, StartNum, StartDate, Rate) VALUES (" & TextBox1.Text & ",'" & TextBox2.Text & "','" & TextBox3.Text & "'," & Me.DropDownList1.SelectedItem.Value & "," & TextBox4.Text & ",'" & dob & "'," & TextBox5.Text & ")", con)
            If i = True Then





                com.ExecuteScalar()
                i = False
            End If

        End Using
        con.Close()

    End Using

End Sub

Upvotes: 0

ChrisLively
ChrisLively

Reputation: 88044

Well... there are lots of problems. The first of which is the potential for SQL Injection, you should be using named parameters. Another is that the line about Dim com As New... should also be in a Using clause.

However, nothing in that bit of code suggests that it is inserting more than 1 record. I suggest you put a break point on the ExecuteNonQuery line and see what's going on.

Upvotes: 2

Automate This
Automate This

Reputation: 31364

Have you checked to see if your block of code is being called more than once? One quick way is to put a alert box inside so you can count the times it runs.

Upvotes: 4

Related Questions