Search code examples
vb.netwinformscomboboxincrement

Visual Basic 2008 Combobox item history track (winforms)


Is there any method which lets you know the previous selection before last selection in a combobox?

For example let's say a combobox have 3 items : 1,2,3 When selecting item 2 and then 3 (from the dropdown combobox list) I want to know that the previous item after selecting item 3 was the item 2.

Can somebody help me please? I will use this in order to decrease/increase quantities in a Shopping Basket. When the user selects a product the quantity automatically must decrease but if the user changes to another product the quantity of the previous one must be increased again in order to avoid consistency issues.


Solution

  • Something like this might help, I'm using a stack so you can see the last added entry. EDIT: On the init, I set an index tag to the combo boxes so you can add to the stack for that combo box in the array. EDIT EDIT: I have added so it searches the form for all the combo box controls and adds them, so you don't have to add the tags or combo boxes manually yourself.

     Dim lastSelectedArr() As Stack(Of String)
    
    Public Sub New()
    
        ' This call is required by the designer.
        InitializeComponent()
    
        ' Add any initialization after the InitializeComponent() call.
        Dim index As Integer = 1
    
        Dim combos As New List(Of ComboBox)
    
        For Each c As Control In Me.Controls
            If (c.GetType() = GetType(ComboBox)) Then
                Dim combo As ComboBox = CType(c, ComboBox)
                combo.Tag = index
                combos.Add(CType(c, ComboBox))
                index += 1
            End If
        Next
    
    
        ReDim lastSelectedArr(combos.Count - 1)
    
    
        For i As Integer = 0 To lastSelectedArr.Length - 1
            lastSelectedArr(i) = New Stack(Of String)
        Next
    
    
    
    End Sub
    
    
    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged, ComboBox2.SelectedIndexChanged
    
        Dim cb As ComboBox = CType(sender, ComboBox)
    
    
        Dim CBID As Integer = CInt(cb.Tag) - 1
    
        lastSelectedArr(CBID).Push(cb.SelectedItem)
    
    
    
        Dim retStr As String = String.Empty
    
        For Each value As String In lastSelectedArr(CBID)
            retStr = retStr + value + ","
        Next
    
        MessageBox.Show(retStr)
    End Sub