I'm trying to insert data from a datagridview control into my SQL database. The code is as follows:
Private Sub MCmdSoftwareSave_Click(sender As Object, e As EventArgs) Handles MCmdSoftwareSave.Click
Dim ID As Integer
Dim Name, Edition, Version, SubVersion As String
Try
SQLcmd.Connection = SQLconn
SQLconn.Open()
For row As Integer = 0 To Me.DgdSoftware.Rows.Count - 1
ID = Me.DgdSoftware.Rows(row).Cells(0).Value
Name = Me.DgdSoftware.Rows(row).Cells(1).Value
Edition = Me.DgdSoftware.Rows(row).Cells(2).Value
Version = Me.DgdSoftware.Rows(row).Cells(3).Value
SubVersion = Me.DgdSoftware.Rows(row).Cells(4).Value
SQLcmd.CommandText = "INSERT INTO Software(ID,Name,Edition,Version,SubVersion) VALUES('" & ID & "','" & Name & "','" & Edition & "','" & Version & "','" & SubVersion & "')"
SQLcmd.ExecuteNonQuery()
Next
MsgBox("The infomration was successfully added to the Software database.", MsgBoxStyle.Information, "Successful Operation")
Catch ex As Exception
MessageBox.Show(ex.Message)
SQLconn.Close()
End Try
End Sub
This works when the table is empty, but it also adds another record where the "ID" (Primary key) is 0 and the rest of the fields in that record are null, before adding the desired data.
If I then try to add more data, I get a message saying I cannot add data to the database where the ID of the current record being saved matches that of an ID in the database (i.e. it's trying to re-save the existing data into the table).
What I want to be able to do is load up a form where all the data in the table is loaded into the datagridview control. I then want to be able to add to that table using the same datagridview control by putting in new records, without the code trying to save the existing data. I also want to be able to edit and delete the data in the datagridview control.
Is there any way to do this effectively?
Many thanks,
James