我遇到了麻烦。我有一个datagridview,显示了来自数据库sql server的所有数据。但是当我尝试在datagridview中插入并保存新行一个或多个数据时,数据库datagridview中显示的前一个插入数据会再次插入我的新行数据。
我只想插入并保存新的行数据,而不是我以前的数据。 请帮帮我!
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
cmd = New SqlCommand("Insert into DataSK values (@NIK, @Name, @Address, @Email, @Status)", con)
cmd.Parameters.Clear()
cmd.Parameters.Add("@NIK", SqlDbType.VarChar, 20).Value = dgv.Rows(row).Cells("NIK").Value
cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50).Value = dgv.Rows(row).Cells("Name").Value
cmd.Parameters.Add("@Address", SqlDbType.VarChar, 50).Value = dgv.Rows(row).Cells("Address").Value
cmd.Parameters.Add("@Email", SqlDbType.Char, 50).Value = dgv.Rows(row).Cells("Email").Value
cmd.Parameters.Add("@Status", SqlDbType.VarChar, 10).Value = dgv.Rows(row).Cells("Status").Value
cmd.ExecuteNonQuery()
End Sub
答案 0 :(得分:0)
这样的事情可以帮助你。
Imports System.Data.SqlClient
Public Class Form1
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim cmdBuilder As SqlCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connetionString = "Data Source=ServerName;Initial Catalog=YourDatabaseName;Trusted_Connection=True;"
connection = New SqlConnection(connetionString)
sql = "Select * from Products"
Try
connection.Open()
adapter = New SqlDataAdapter(Sql, connection)
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
connection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'NOTE: for this code to work, there must be a PK on the Table
Try
cmdBuilder = New SqlCommandBuilder(adapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
adapter.Update(changes)
End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class