標題: [心得分享] VB + Access Database - Table to Table with DataGridView [打印本頁]
作者: X-Engineer 時間: 2016-7-26 11:04 標題: VB + Access Database - Table to Table with DataGridView
一個Database, 兩個Table, 兩個DataGridView, 一個Windows Form.
兩個Table的資料互抄並刪除, 顯示返在兩個DataGridView.
不知是否蠢的寫法, 但做到, 大家可討論一下吧.
Private Sub btnMove_Click(sender As Object, e As EventArgs) Handles btnMove.Click
Dim rowindex As String
Dim found As Boolean = False
For Each row As DataGridViewRow In DataGridView2.Rows
If row.Cells.Item("DataGridViewTextBoxColumn1").Value = DataGridView2.CurrentCell.Value Then
rowindex = row.Index.ToString()
found = True
Dim result As String = ""
result = row.Cells("DataGridViewTextBoxColumn1").Value.ToString()
Dim newRow As DataSet.Row
newRow = Me.DataSet.A_Table.NewA_TableRow
newRow.IDNumber = row.Cells("DataGridViewTextBoxColumn1").Value.ToString()
newRow.CName = row.Cells("DataGridViewTextBoxColumn2").Value.ToString()
newRow.EName = row.Cells("DataGridViewTextBoxColumn3").Value.ToString()
newRow.PhoneNumber = row.Cells("DataGridViewTextBoxColumn4").Value.ToString()
newRow.Address = row.Cells("DataGridViewTextBoxColumn5").Value.ToString()
' Add the row to the B table
Me.DataSet.A_Table.Rows.Add(newRow)
' Save the new row to the database
Me.A_TableTableAdapter.Update(Me.DataSet.A_Table)
Dim con As OleDbConnection
Dim com As OleDbCommand
lbl.Text = row.Cells("DataGridViewTextBoxColumn1").Value.ToString()
con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=|DataDirectory|\TEST.accdb")
com = New OleDbCommand("delete * from B_Table where IDNumber =" + lbl.Text, con)
con.Open()
com.Parameters.AddWithValue("IDNumber", lbl.Text)
com.ExecuteNonQuery()
MsgBox("Record Moved to A Table")
con.Close()
Exit For
End If
Next
If Not found Then
MsgBox("Item not found.")
End If
Me.B_TableTableAdapter.Fill(Me.DataSet.B_Table)
DataGridView1.Refresh()
DataGridView2.Refresh()
End Sub
