Mysql 在Vb.net的Datagridview行中添加记录
您好,我的vb.net表单中有Datagridview,我想将MySQL表中的数据显示到vb.net的Datagridview(Dgv)中,但问题是当我更新或删除Dgv中的记录时,我获取的当前记录会添加更多当前记录的显示。我这样写代码是因为我要在上面添加更多的函数,我知道我可以使用MySqlDataAdapter和DataSet来完成这项工作,然后填充代码的datagridview,但我使用它来添加更多的函数,现在我如何更新/删除一条记录而不添加更多当前获取的行。或者将行的Mysql 在Vb.net的Datagridview行中添加记录,mysql,.net,vb.net,datagridview,Mysql,.net,Vb.net,Datagridview,您好,我的vb.net表单中有Datagridview,我想将MySQL表中的数据显示到vb.net的Datagridview(Dgv)中,但问题是当我更新或删除Dgv中的记录时,我获取的当前记录会添加更多当前记录的显示。我这样写代码是因为我要在上面添加更多的函数,我知道我可以使用MySqlDataAdapter和DataSet来完成这项工作,然后填充代码的datagridview,但我使用它来添加更多的函数,现在我如何更新/删除一条记录而不添加更多当前获取的行。或者将行的 Dim SQL as
Dim SQL as String = "Select * from employee"
Dim cmd as MySqlCommand = new MySqlCommad(SQL, connection)
Dim reader as MysqlDataReader = cmd.executeReader()
Dim empId, empName, empAddress as String
with reader.Read
empId = reader("empId")
empName = reader("name")
empAddress = reader("address")
Dim row() As String
row = new String() {empId, empName, empAddress}
DataGridView1.Rows.Add(row)
End While
reader.close()
cmd.close()
我知道问题是成行的。添加
增加:
当前,此功能是显示数据,当事件或按钮被单击时,将再次调用此子项。无需添加更多显示
Dim SQL as String = "Select * from employee"
Dim cmd as MySqlCommand = new MySqlCommad(SQL, connection)
Dim reader as MysqlDataReader = cmd.executeReader()
Dim empId, empName, empAddress as String
'before adding new row in datagridview add this code
DataGridView1.Rows.clear();
with reader.Read
empId = reader("empId")
empName = reader("name")
empAddress = reader("address")
这样,它将删除行的旧值,然后在数据库中添加新值,这应该可以满足您的需要。您可以轻松地从sql server选择到datagridview,更改数据,并将更改从datagridview传递到sql server
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='your_server';Initial Catalog='your_database';Trusted_Connection=True;"
connection = New SqlConnection(connetionString)
sql = "Select * from Product"
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
如果将
emplypyee
表加载到数据表,则不必向DGV添加行,您可以将该表绑定到该表,它将自动显示所有内容。要添加一个新的emp,请添加一个新的DataRow当前我不使用DataTable,因为我要过滤其中的一些数据示例,EmpAddress是从我们这里来的,我不会在datagrid中显示,但我会将其传递给变量以备将来使用