2

I have a ListBox with various rows of data (items that someone is buying, basically), and when the user clicks on a row it populates a textbox on the side with the quantity of how many of that thing he's buying. For example, one row might be "Pencils, $5, 3" and clicking the row makes "3" appear in the textbox.

If the user changes that 3 to a 7, for example, I want that to be put back into the row, so we now have "Pencils, $5, 7"

How do I do that?

1
  • 1
    This looks very like a set up where a subform bound to the purchases table would be the easiest solution.
    – Fionnuala
    Commented Aug 2, 2010 at 19:48

1 Answer 1

0

You need to program the Listbox's SelectedIndexChanged event and the Textbox's TextChanged event. Here's your snippet:

Private Sub ListBox1_SelectedIndexChanged( _
    ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles ListBox1.SelectedIndexChanged

    // Exit if no item is selected
    If ListBox1.SelectedItem Is Nothing Then Exit Sub

    // Get the item's text
    Dim item As String = ListBox1.SelectedItem.ToString

    // Keep only the last part
    item = item.Substring(item.LastIndexOf(", ") + 2)

    // Update the textbox
    TextBox1.Text = item

End Sub

Private Sub TextBox1_TextChanged( _
    ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles TextBox1.TextChanged

    // Exit if no item is selected
    If ListBox1.SelectedItem Is Nothing Then Exit Sub

    // Get the item's text, removing the last part
    Dim item As String = ListBox1.SelectedItem.ToString
    item = item.Substring(0, item.LastIndexOf(", ") + 2)

    // Add the numerical value of the textbox's text
    item &= Val(TextBox1.Text)

    // Get the index of the selected item
    Dim index As Integer = ListBox1.SelectedIndex

    // Remove the old item, add the new one and select it
    ListBox1.Items.RemoveAt(index)
    ListBox1.Items.Insert(index, item)
    ListBox1.SelectedIndex = index

End Sub
4
  • 1
    You don't need to remove the item and reinsert it. You could just modify it and refresh the listbox. That will do the same. Commented Aug 2, 2010 at 13:42
  • This post is not VBA code. Neither the SelectedIndexChanged not TextChanged events exist in VBA. Please read questions more carefully before posting. Commented Aug 2, 2010 at 19:22
  • @David-W-Fenton: When I replied, there was a VB.NET tag. Don't be so hasty judging other peoples' answers.
    – Anax
    Commented Aug 2, 2010 at 19:29
  • The original post also had [VBA] [MS-ACCESS] and [ACCESS-VBA]. Those are some pretty big clues that the [VB.NET] tag was out of place. Commented Aug 3, 2010 at 19:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.