views:

36

answers:

1

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?

A: 

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
Anax
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.
David Brunelle
This post is not VBA code. Neither the SelectedIndexChanged not TextChanged events exist in VBA. Please read questions more carefully before posting.
David-W-Fenton
@David-W-Fenton: When I replied, there was a VB.NET tag. Don't be so hasty judging other peoples' answers.
Anax
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.
David-W-Fenton