2016-06-11 94 views
-1

你好我的DataGridView在我的vb.net的形式,我想从MySQL表中的数据显示,以Vb.net的DataGridView中(DGV),但问题是我何时更新或删除Dgv中的记录,我获取的当前记录是添加更多当前记录的显示。我写这篇文章这样的代码,因为我要上添加更功能,我知道我能做到这一点使用和MySqlDataAdapter的数据集,然后填写该代码的datagridview的,但我用它来增加更多的功能,现在如何更新/删除一条记录,但不添加我当前获取的更多行。或加倍行的在Vb.net添加记录中的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

补充: 目前的这个功能是显示数据,并在事件或按钮是点击这个小组将会再次调用。没有增加更多的显示。

+0

如果您加载'emplpyee'表到DataTable,你不必行添加到DGV,你可以将表绑定到它,它会自动地显示一切。要添加新的EMP,添加一个新的DataRow – Plutonix

+0

目前,因为我会过滤掉一些它的数据例如我不使用数据表,我的EmpAddress是从美国,我不打算在DataGrid中显示,但我会将其传递给变量以备将来使用 – Max

回答

1
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") 

,这样它会删除该行的旧值,然后在数据库

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