不绑定记录集获取datagrid某行某列的内容
2007-11-11 09:34:50 来源:WEB开发网获取Dvatagrid第r行c列的内容可以用下面代码获得
DataGrid2.Col = r
DataGrid2.Row = c
msgbox DataGrid2.Text
但如果datagrid2中有滚动条,要得到滚动下面某行某列的内容时,系统会提示说:行号无效!
这是由于DataGrid2.Row只能在[1,datagrid.visiblerows]间取值。当行号大于visiblerows(默认18)时,系统就会报错。这种情况一般使用DATAGRID绑定的记录集来移动当前记录指针实现。下面给出一种利用DATAGRID滚动条事件的方法解决这个问题:
Private Sub Command1_Click()
Dim r As Integer, temp As String
Randomize
r = Int(Rnd * DataGrid1.ApproxCount + 1)'任意行
DataGrid1.Scroll -DataGrid1.LeftCol, r - DataGrid1.FirstRow'第一行第一列
temp = InputBox("DATAGRID 目前随机定位在第" & r & "行第1列,你想现在移动到第几行,第几列?", "提示", Int(Rnd * 1000 + 1) & "," & Int(Rnd * DataGrid1.Columns.Count + 1))
'随机输入行列
MsgBox "第" & Split(temp, ",")(0) & "行第" & Split(temp, ",")(1) & "列的值为" & gettext(DataGrid1, Split(temp, ",")(0), Split(temp, ",")(1))'选定该行该列并取其值
End Sub
Function gettext(ByVal dgrid As DataGrid, ByVal r As Integer, ByVal c As Integer) As String'获取DGRID第r行c列的内容
dgrid.Scroll 0, r - dgrid.FirstRow'从FirstRow行下滚r-FirstRow行
dgrid.Col = c - 1'选C列
dgrid.Row = 0 '选第一个可见行
gettext = dgrid.Text'取值
End Function
Private Sub Form_Load()'填充一个datagrid
Dim adoRecordset As New ADODB.Recordset
Dim i As Integer, j As Integer, k As Integer
For i = 0 To 5 '为Recordset六个字段,即为 DataGrid 添加六列
adoRecordset.Fields.Append "n * " & i + 1, adVariant, , adFldMayBeNull + adFldIsNullable + adFldUpdatable
Next i
With adoRecordset
.Open
For j = 1 To 1000
.AddNew
.Fields(0) = j
.Fields(1) = 2 * j
.Fields(2) = 3 * j
.Fields(3) = 4 * j
.Fields(4) = 5 * j
.Fields(5) = 6 * j '加1000条记录,即为 DataGrid 添加1000行
Next j
.MoveFirst
End With
Set DataGrid1.DataSource = adoRecordset '绑定 DataGrid 的数据源
End Sub
更多精彩
赞助商链接