Identify and populate a listbox

前端 未结 3 1902
粉色の甜心
粉色の甜心 2021-01-03 11:26

It\'s a riddle for me: what is the syntax to populate a listbox? But first: how do you identify a listbox? In many forums I read: ListBox1.Additem... But how do

3条回答
  •  盖世英雄少女心
    2021-01-03 12:13

    That's the default name for a ListBox control when you add it to your form. VB and VBA automatically name new or unnamed controls with the name of the type of control, suffixed with an integer identifier.

    It's completely irrelevant what your control is called. The point of the sample code is to demonstrate a concept. You should replace ListBox1 with whatever your control is named.

    And you should definitely name your controls something other than the default, because as you observe here, it's not very descriptive.

    It used to be recommended by everyone to name controls following some type of quasi-Hungarian notation with a 3-letter prefix indicating the type of control, followed by your regular descriptive name. Over the past few years, there's been a big backlash against anything that looks like Hungarian notation, but I think it's still quite useful with regards to naming GUI controls, so I still use it. For a ListBox control, I might call it something like: lstCustomers or lstItemsForSale. But it's completely optional: again, what you choose to name your controls is irrelevant to how the code works or how the application will behave.

    So, to populate a listbox in VB 6 and/or VBA, you'd use the following code, where myListBox is the name of your ListBox control:

    ' Add an item to the end of the list
    myListBox.AddItem "Peaches"
    
    ' Insert an item at the top of the list
    myListBox.AddItem "Apples", 0
    
    ' Remove the first item in the list
    myListBox.RemoveItem 0
    

提交回复
热议问题