Loogawa
Loogawa

Reputation: 389

Need to bind/populate combobox in WPF forms, ideally with value and display

My application for other reasons isn't set up with the MVVM architecture and I'm not able to at this time. The only thing that I need to modify now is a combobox to be populated from the database (it is stored in a OracleDataReader). I would like to just programmatically add items to the combobox from looping through this OracleDataReader, or bind it in some way.

Public Sub LoadLocationCombo()
    Dim rs As OracleDataReader
    Dim dt As New DataTable()
    Dim dr As DataRow
    Dim lstItems As New ArrayList

    rs = objClsDB.LocationCombo

    dt.Load(rs)

    dt.Columns("description").AllowDBNull = True
    dt.Columns("value_id").AllowDBNull = True
    dt.Columns("description").DefaultValue = ""
    dt.Columns("value_id").DefaultValue = 0

    dr = dt.NewRow

    dr("description") = ""
    dr("value_id") = 0

    dt.Rows.InsertAt(dr, 0)

    cboLocation.ItemsSource = dt.DefaultView
    cboLocation.DisplayMemberPath = "description"
    cboLocation.SelectedValuePath = "value_id"

End Sub

That is my current method, I'm trying to add a blank row at the top as well. This makes the combo have what looks like multiple rows but Nothing is in the selected value and nothing displays.

Edit: If I remove the cboLocation.DisplayMemberPath and .SelectedValuePath then the combobox is filled with a bunch of System.Data.Common.DataRecordInternal

Upvotes: 0

Views: 2009

Answers (1)

felipeAS
felipeAS

Reputation: 59

First, the DefaultView of a DataTable will return an object of type DataView, and DataView does not have properties called "description" or "value_id". That's why nothing is selected, and nothing is displayed.

You might build some list and fill it with the datatable values, for example:

Dim listToFillCombo As New List(Of KeyValuePair(Of Integer, String))

For Each dr As DataRow In dt.Rows
    listToFillCombo .Add(New KeyValuePair(Of Integer, String)(CInt(dr("value_id")), dr("description").ToString))
Next

Then the comboBox binding

cboLocation.ItemsSource = listToFillCombo 
cboLocation.DisplayMemberPath = "Value"
cboLocation.SelectedValuePath = "Key"

Upvotes: 2

Related Questions