AdorableVB
AdorableVB

Reputation: 1393

Get one everytime I iterate through a data table

Here's my current code:

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

If you run this code, it gives all the names in the MarkerName field. Anyway, how can I get only one as I press SpaceKey then the next one if I press it again? Sorry, I don't really have an idea.

Upvotes: 0

Views: 74

Answers (2)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56717

The problem is that you iterate over all the items using the For Each loop. That's why you get all the entries if SPACE is pressed. I guess your problem is how to remember which entry you returned last time :-)

You need to declare a static variable that remembers the last index:

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

This "remembers" the last index returned until the function is called next time. The need for a "global" variable outside this function is removed as the local variable is static. It is thus valid also between calls to the function.

Upvotes: 1

x2.
x2.

Reputation: 9668

Declare variable for position outside of this function.

Dim pos As Integer

Then in function:

If (keyData = Keys.Space and pos < markerDtable.Rows.Count) Then
    pos += 1
    comboSearchMarker.Text = markerDtable.Rows(pos).Item("MarkerName")
End If

Upvotes: 0

Related Questions