Ask the Expert

Using an array, how can I create a combo box that lists a dropdown menu for units of length?

I'm trying to create a combo box that lists a dropdown menu. The dropdown menu is going to contain units of length -- such as mm., cm., in., ft., mi., km., etc. How would I do this using an array? Thanks! Here's what I have thus far:

Private Sub Form_Load()
    Dim Length(6) As Integer
    Dim J As Integer
        Length(1) = Millimeter
        Length(2) = Centimeter
        Length(3) = M
        Length(4) = dm
        Length(5) = dm
        Length(6) = mm
            For J = Length(1) To Length(6)
                cboStart.AddItem J
            Next J
End Sub

You were very close. A couple of tweaks to your existing code yields something that does what you want, I think:

Private Sub Form1_Load(...) Handles MyBase.Loade
  Dim Length(6) As String
  Dim J As Integer
  Length(1) = "Millimeter"
  Length(2) = "Centimeter"
  Length(3) = "M"
  Length(4) = "cm"
  Length(5) = "dm"
  Length(6) = "mm"
  For J = 1 To 6
    cboStart.Items.Add(Length(J))
  Next J
  cboStart.SelectedIndex = 0
End Sub

If you wanted to get fancy, you could use an ArrayList and data binding, saving yourself the for-loop:

Private Sub Form1_Load(...) Handles MyBase.Load
  Dim Length As New ArrayList()
  Length.Add("Millimeter")
  Length.Add("Centimeter")
  Length.Add("M")
  Length.Add("cm")
  Length.Add("dm")
  Length.Add("mm")
  cboStart.DataSource = Length
End Sub

If you didn't already have the array of values lying around, you could also add them to the combo box directly:

Private Sub Form1_Load(...) Handles MyBase.Load
  cboStart.Items.Add("Millimeter")
  cboStart.Items.Add("Centimeter")
  cboStart.Items.Add("M")
  cboStart.Items.Add("cm")
  cboStart.Items.Add("dm")
  cboStart.Items.Add("mm")
  cboStart.SelectedIndex = 0
End Sub

This was first published in December 2002

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: