.net 每次我遍历数据表时都会得到一个
以下是我当前的代码:.net 每次我遍历数据表时都会得到一个,.net,vb.net,for-loop,datatable,.net,Vb.net,For Loop,Datatable,以下是我当前的代码: Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean For Each item In markerDtable.Rows If keyData = Keys.Space Then comboSearchMarker.Text = item("MarkerName") ' Gets t
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
For Each item In markerDtable.Rows
If keyData = Keys.Space Then
comboSearchMarker.Text = item("MarkerName") ' Gets the items in MarkerName field but I need only one at a time.
End If
Next
End Function
如果运行此代码,它会在
MarkerName
字段中给出所有名称。无论如何,当我按下SpaceKey
时,我怎么能只得到一个呢?如果我再按一次,怎么能得到下一个呢?抱歉,我真的不知道。为该函数之外的位置声明变量
Dim pos As Integer
然后在功能上:
If (keyData = Keys.Space and pos < markerDtable.Rows.Count) Then
pos += 1
comboSearchMarker.Text = markerDtable.Rows(pos).Item("MarkerName")
End If
If(keyData=Keys.Space和pos
问题在于您使用For Each
循环遍历所有项目。这就是为什么按下SPACE
时会显示所有条目。我猜您的问题是如何记住上次返回的条目:-)
您需要声明一个静态变量来记住最后一个索引:
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
Static lastEntryReturned As Integer = 0
If keyData = Keys.Space Then
comboSearchMarker.Text = markerDTable.Rows(lastEntryReturned).Item("MarkerName")
lastEntryReturned += 1
If lastEntryReturned >= markerDTable.Rows.Count
lastEntryReturned = 0
End If
End If
End Function
这将“记住”在下次调用函数之前返回的最后一个索引。由于局部变量是静态的,因此不再需要此函数之外的“全局”变量。因此,它在函数调用之间也是有效的。该代码毫无意义。在你的循环中,你甚至没有评估
项目
-那么目的是什么呢?@DonA更新了我的问题。对不起,复制粘贴再次命中:-)修复。它跳过了一个项目。对我来说没关系,但我想,如果我的行.count
是一个偶数,那么它就不会得到奇数了?我将编辑我的答案以避免出现这种情况。问题是我将代码放在处理空格键的代码之外的incrementlasentryreturned
。因此,无论按哪个键,变量都会递增。
Dim pos As Integer