Search code examples
wpfvb.netdata-binding

DataTable to Combobox - SelectedValue not being set in UI, two values returned


I know this is an almost persistent issue cropping up with SelectedItem with regards to databound ComboBox elements, but I'm also now struggling with this issue.

XAML:

<ComboBox x:Name="Price_List" BorderBrush="Gainsboro" Margin="5"  Grid.Column="1" Grid.Row="0" Grid.ColumnSpan="2" Background="{x:Null}"/>

Code-Behind:

Using Sql As New SqlClient.SqlConnection(ConnStr)
    Sql.Open()

    Using sqlcmd As New SqlClient.SqlCommand(SQLQuery, Sql)

        Dim DA As New SqlDataAdapter
        Dim DS As New DataSet
        Dim DT As New DataTable

        With DT.Columns
            .Add("price_list")
            .Add("description")
        End With

        With Price_List
            .ItemsSource = DT.DefaultView
            .DisplayMemberPath = "description"
            .SelectedValuePath = "price_list"
        End With

        DA.SelectCommand = sqlcmd
        DA.Fill(DT)
    End Using
End Using

SelectedValue is sort of working, as evidenced by a Debug.Print of the value in the SelectionChanged, but it is returning two values (one NULL) on each change - why would this be?

Obviously in this regard, the SelectedValue is always going to be different to the DisplayMember, so how do I force WPF to display it?


Solution

  • If you move it back insert some breakpoints in Main_Tabs_SelectionChanged and ensure the code is only executing once.

    see https://social.msdn.microsoft.com/Forums/en-US/22e16180-914b-4b07-939e-b17ce692cf11/tab-control-selectionchanged-event-fires-a-combos-selectionchanged-event-fires?forum=wpf