Populating a Combo Box from DataReader

  • Thread starter Thread starter Teo
  • Start date Start date
T

Teo

Hi! I am trying to populate a combo box using a data reader.
I want to add the Item as well as the ValueMember. Will this do the trick?

Do While oDr.Read

cmbestudiante.Items.Add(oDr.Item("Estudiante_Apellido") + ", " +
oDr.Item("Estudiante_Nombre"))

cmbestudiante.ValueMember = oDr.Item("Estudiante_ID")





Loop
 
I presume you're working in vb.net rather than asp.net...

Create a class:

Public Class clTest
Private m_Text as String
Private m_Value as Integer

Public Sub New (ByVal Text as string, ByVal Value as intger)
m_Text = Text
m_Value = Value
End Sub

Public Overrides Function ToString() As String
Return m_Text
End Function

Public Overrides Function Value() As Integer
Return m_Value
End Function
End Class

You can also add as many other properties per item as you wish (making it
more versatile than in VB6).

Then to populate the control from a datareader...

ComboBox.ValueMember = "Value"

While drTest.Read
ComboBox.items.Add(New clTest(drTest("TextField"),
drTest("ValueField")))
End While

Jobs a good'n'!

To grab the values use; cbTest.SelectedItem.Value for the ID or
cbTest.SelectedItem.ToString() for the
text value and so on...

HTH, Carl
 
Is there a way to fix the current code without having to build a new class?
Just maybe save the first set of values into a variable and then also create
a variable to capture the ID from the DB into a variable and then save it
into the ValueMember property?
I think since it's a loop it should be able to be done. Not sure though,
I've worked a lot with ColdFusion and a little with ASP.
Thanks much,
Teo
 
Back
Top