Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Beginner
Apr 7, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Simplify Programatic Selection in Combos

Here's a useful procedure to position a ComboBox according to a value of the ItemData property or the List property. It's useful to position a ComboBox with values taken from a database, and this way, become independent of the index property. For example, you might fill a ComboBox with the serial port's baud speeds, including a description in List and the value in bauds in ItemData:
Public Sub LlenarCombo(pCombo As ComboBox)
	With pCombo
		.AddItem "1200 bps"
		.ItemData(0) = 1200
		.AddItem "2400 bps"
		.ItemData(1) = 2400
		.AddItem "4800 bps"
		.ItemData(2) = 4800
		.AddItem "9600 bps"
		.ItemData(3) = 9600
		.AddItem "14400 bps"
		.ItemData(4) = 14400
		.AddItem "28800 bps"
		.ItemData(5) = 28800
		.ListIndex = 0
	End With
End Sub
Public Sub PosicionarCombo(pCombo As _
	ComboBox, ByVal pValor As Variant)
	Dim i As Integer
	If IsNumeric(pValor) Then
		' Search by ItemData
		For i = 0 To pCombo.ListCount - 1
			If pCombo.ItemData(i) = pValor Then
				pCombo.ListIndex = i
				Exit For
			End If
		Next i
		' Search by List 
		For i = 0 To pCombo.ListCount - 1
			If pCombo.List(i) = pValor Then
				pCombo.ListIndex = i
				Exit For
			End If
		Next i
	End If
End Sub
Private Sub cmdPosItemData_Click()
	PosicionarCombo cboTest, 9600
End Sub
Private Sub cmdPosList_Click()
	PosicionarCombo cboTest, "4800 bps"
End Sub
Diego M.
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date