在Vb.net中的Datagridview Row中添加记录

时间:2016-06-11 15:03:17

标签: mysql .net vb.net datagridview

您好我的vb.net表单中有Datagridview,我想将数据从MySQL表显示到Vb.net的Datagridview(Dgv),但问题是我在Dgv中更新或删除当前记录的记录我获取的是添加更多当前记录的显示。我这样编写这段代码是因为我要在其上添加更多功能,我知道我可以使用MySqlDataAdapter和DataSet来完成这个,然后填充这段代码的datagridview但是我用它来添加更多功能,现在我该如何更新/删除记录而不添加我当前获取的更多行。或加倍行

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()

我知道问题出在Rows.Add

添加了: 目前,其功能是显示数据,当事件或按钮单击时,将再次调用此Sub。没有添加更多显示。

2 个答案:

答案 0 :(得分:1)

Sheet1

这样它将删除行的旧值,然后在数据库中添加新值

答案 1 :(得分:1)

这应该做你想要的。您可以轻松地从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