一般对于这些都是用普通控件就可以。因为代码量其实是一样的。而且用SQL语句写入combobox控件还方便控制,并且可以释放数据源。减少控件内存占用率。
新建一个模块,代码如下:这个是通用数据库链接函数,用的时候只要调用就可以了。很方便的。
'传递参数SQL传递查询语句,MsgString传递查询信息。自身以一个数据集对象的形式返回
Public Function ExecuteSQL(ByVal SQL As String, MsgString As String) As ADODB.Recordset
Dim Cnn As ADODB.Connection '定义连接
Dim Rst As ADODB.Recordset
Dim sTokens() As String '定义字符串
On Error GoTo ExecuteSQL_Error '异常处理
sTokens = Split(SQL) '用Split函数产生一个包含各个子串的数组
Set Cnn = New ADODB.Connection '创建连接
Cnn.Open ConnectString
If InStr("INSERT,DELETE,UPDATE", UCase$(sTokens(0))) Then '判断字符串中是否含有指定内容
Cnn.Execute SQL '执行查询语句
MsgString = sTokens(0) & "query successful" '返回查询信息
Else
Set Rst = New ADODB.Recordset '闯将数据集对象
Rst.Open Trim$(SQL), Cnn, adOpenKeyset, adLockOptimistic '返回查询结果
Set ExecuteSQL = Rst '返回记录集对象
MsgString = "查询到" & Rst.RecordCount & " 条记录"
End If
ExecuteSQL_Exit:
Set Rst = Nothing '清空数据集对象
Set Cnn = Nothing '中断连接
Exit Function
ExecuteSQL_Error: '判断错误类型
MsgString = "查询错误:" & Err.Description
Resume ExecuteSQL_Exit
End Function
'连接数据库
Public Function ConnectString() As String
'返回一个数据库连接
ConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password= abcd ;Data Source=" & App.Path & "\data.mdb"
End Function
窗体代码
Private Sub Command1_Click()
Dim TxtSQL As String
Dim Mrc As New ADODB.Recordset
Dim MsgText As String
TxtSQL = "select * from admin where Name like'%" & (Me.TxtFindWord.Text) & "%'"
Set Mrc = ExecuteSQL(TxtSQL, MsgText)
Do While Not Mrc.EOF
Me.Combo1.AddItem Mrc("name")
Mrc.MoveNext
Loop
End Sub
你试试~ 我用的代码,应该可以的~~
Private Sub Form_Load()
Adodc1.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=f:\mysany\qq1.mdb;Persist Security Info=False"
Adodc1.CommandType = adCmdText
Adodc1.RecordSource = "select * from 表1"
Set DataGrid1.DataSource = Adodc1
Me.Refresh
End Sub