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
Dig deeper on .NET tutorials, guides and quizzes
Related Q&A from Chris Sells
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.