獲取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