'首先。datagrid其实是用recordset记录集来控件的。datagrid1的allowdelete和allowupdate都设置为false,然后加代码如下(command1的代码只是程序控制下的新增示例):它就只能新增: Option Explicit Dim N As Long Dim conn As ADODB.Connection Dim rs As ADODB.RecordsetPrivate Sub Command1_Click() N = N + 1 With rs .AddNew .Fields("id") = N .Fields("idvalue") = "你好!" .Update End With End SubPrivate Sub DataGrid1_RowColChange(LastRow As Variant, ByVal LastCol As Integer) With DataGrid1 If .Row >= N Then .AllowUpdate = True .AllowDelete = True .AllowUpdate = True Else .AllowUpdate = False .AllowDelete = True .AllowUpdate = True End If End With End SubPrivate Sub Form_Load() '使用编号来控制Datagrid的行列,使最后新增的一列才可以编辑: Dim strSQL As String strSQL = App.Path & "\A.mdb" strSQL = Replace(strSQL, "\\", "\") Set conn = New ADODB.Connection Set rs = New ADODB.Recordset
With conn If .State = 1 Then .Close End If .CursorLocation = adUseClient .ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=" & strSQL .Open End With With rs .Open "SELECT Id, IDvalue FROM Table1 ORDER BY Id;", conn, adOpenStatic, adLockOptimistic If .BOF And .EOF Then N = 0 Exit Sub End If .movefirst .movelast N = .recordcount End With
With DataGrid1 Set .DataSource = rs .AllowDelete = False .AllowUpdate = False End With
End Sub
private sub datagrid1_click dim N1 as integer N1=datagrid1.columns.col datagrid1.columns.item(N1)=combo1.text end sub'注意:调试时发现上述赋值有些冲突,因为前面设置.allowupdate =false,不是任何一行都能赋值。要将combo1 中的数据传递给当前选中的 cell,使用datagrid绑定的rs来做一容易得多。但这需要判断rs的行号(绝对位置,和排序有关)。
怎样都 combo1 中的数据传递给当前选中的 cell
Option Explicit
Dim N As Long
Dim conn As ADODB.Connection
Dim rs As ADODB.RecordsetPrivate Sub Command1_Click()
N = N + 1
With rs
.AddNew
.Fields("id") = N
.Fields("idvalue") = "你好!"
.Update
End With
End SubPrivate Sub DataGrid1_RowColChange(LastRow As Variant, ByVal LastCol As Integer)
With DataGrid1
If .Row >= N Then
.AllowUpdate = True
.AllowDelete = True
.AllowUpdate = True
Else
.AllowUpdate = False
.AllowDelete = True
.AllowUpdate = True
End If
End With
End SubPrivate Sub Form_Load()
'使用编号来控制Datagrid的行列,使最后新增的一列才可以编辑:
Dim strSQL As String strSQL = App.Path & "\A.mdb"
strSQL = Replace(strSQL, "\\", "\")
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
With conn
If .State = 1 Then
.Close
End If
.CursorLocation = adUseClient
.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=" & strSQL
.Open
End With With rs
.Open "SELECT Id, IDvalue FROM Table1 ORDER BY Id;", conn, adOpenStatic, adLockOptimistic
If .BOF And .EOF Then
N = 0
Exit Sub
End If
.movefirst
.movelast
N = .recordcount
End With
With DataGrid1
Set .DataSource = rs
.AllowDelete = False
.AllowUpdate = False
End With
End Sub
dim N1 as integer
N1=datagrid1.columns.col
datagrid1.columns.item(N1)=combo1.text
end sub'注意:调试时发现上述赋值有些冲突,因为前面设置.allowupdate =false,不是任何一行都能赋值。要将combo1 中的数据传递给当前选中的 cell,使用datagrid绑定的rs来做一容易得多。但这需要判断rs的行号(绝对位置,和排序有关)。