编辑ListBox的内容

时间:2010-08-02 10:50:23

标签: ms-access vba access-vba

我有一个带有各种数据行的ListBox(基本上是有人购买的物品),当用户点击一行时,它会在侧面填充一个文本框,其中包含他购买的数量。例如,一行可能是“Pencils,$ 5,3”,单击该行会使“3”出现在文本框中。

例如,如果用户将3更改为7,我希望将其重新放入行中,因此我们现在有“铅笔,5美元,7美元”

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您需要对列表框的SelectedIndexChanged事件和文本框的TextChanged事件进行编程。这是你的片段:

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