刘金玉的零基础VB教程084期:
mshflexgrid联动数据库删除
Mshflexgrid属性运用
MSHFlexGrid1.Row 返回当前选中的行号
MSHFlexGrid1.TextMatrix(MSHFlexGrid1.Row, 0)代表返回指定行的第一列的值
删除后的刷新思想
1、数据库删除后,重新进行一遍查询(不推荐,消耗性能大)
2、数据库删除后,直接在mshflexgrid上面进行删除指定行,使用语句MSHFlexGrid1.RemoveItem MSHFlexGrid1.Row
RemoveItem方法后面添加一个索引值,就可以删除指定行
课堂总结
1、掌握两种删除后刷新数据的思想
2、使用RemoveItem方法的时候,删除时候要注意sql语句必须在前面,因为必须要先获取到实际要删除的ID值
文件列表:
界面:
源代码:
Option Explicit Dim sql As String Dim conn As New ADODB.Connection Dim rs As ADODB.Recordset Private Sub Command1_Click() If conn.State = 0 Then conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\Database3.mdb;Persist Security Info=False" conn.Open End If sql = "insert into [users]([username],[password]) values('" & Text1.Text & "','" & Text2.Text & "')" Set rs = New ADODB.Recordset rs.Open sql, conn, adOpenKeyset, adLockBatchOptimistic 'MsgBox "录入成功!" sql = "select * from users" rs.Open sql, conn, adOpenKeyset, adLockBatchOptimistic Set MSHFlexGrid1.DataSource = rs '表头 MSHFlexGrid1.TextMatrix(0, 0) = "唯一编号" MSHFlexGrid1.TextMatrix(0, 1) = "账号" MSHFlexGrid1.TextMatrix(0, 2) = "密码" End Sub Private Sub Command2_Click() If conn.State = 0 Then conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\Database3.mdb;Persist Security Info=False" conn.Open End If Set rs = New ADODB.Recordset sql = "select * from users" rs.Open sql, conn, adOpenKeyset, adLockBatchOptimistic Set MSHFlexGrid1.DataSource = rs '表头 MSHFlexGrid1.TextMatrix(0, 0) = "唯一编号" MSHFlexGrid1.TextMatrix(0, 1) = "账号" MSHFlexGrid1.TextMatrix(0, 2) = "密码" End Sub Private Sub Command3_Click() If conn.State = 0 Then conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\Database3.mdb;Persist Security Info=False" conn.Open End If Set rs = New ADODB.Recordset sql = "delete from [users] where [id]=" & MSHFlexGrid1.TextMatrix(MSHFlexGrid1.Row, 0) rs.Open sql, conn, adOpenKeyset, adLockBatchOptimistic 'Call Command2_Click '方法1 '方法2 MSHFlexGrid1.RemoveItem MSHFlexGrid1.Row End Sub