Nicholas Mott
Nicholas Mott

Reputation: 112

Display and Value Member in combobox c# wpf

I am adding items to a combobox using the code below, but cant work out how to add the display and value members in WPF. I have tried using the

DisplayMemberPath = MedName

and ValueMemberPath= MedID but it still only makes use of the MedName

Any help will be greatly appreciated.

using (SqlConnection conn = new SqlConnection(connection))
            {
                try
                {
                    SqlCommand sqlCmd = new SqlCommand("SELECT MedID, MedName FROM Medication", conn);
                    conn.Open();
                    SqlDataReader sqlReader = sqlCmd.ExecuteReader();

                    while (sqlReader.Read())
                    {
                        comboBox_select_Item.Items.Add(sqlReader["MedName"].ToString());

                    }
                    sqlReader.Close();

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Could not populate medication combobox from database.", ex.ToString());
                }
            }

Upvotes: 2

Views: 9091

Answers (2)

dovid
dovid

Reputation: 6452

the right way is as @JonathaWillcock answer.

but here the minimal changes for see how it work:

XAML

<ComboBox DislayMemberPath="MedName"  SelectedValuePath="MedID"  ... />

in your code, change the loop:

while (sqlReader.Read())
    comboBox_select_Item.Items.Add(new {
         MedName = sqlReader["MedName"].ToString(),
         MedID = sqlReader["MedID"].ToString() 
    });

Upvotes: 1

Jonathan Willcock
Jonathan Willcock

Reputation: 5235

The way I deal with combo boxes of this kind is via a ComboBoxPair class:

public class ComboBoxPair
{
    public string Text { get; set; }
    public int Index { get; set; }

    public ComboBoxPair(string display, int idx)
    {
        Text = display;
        Index = idx;
    }
}

I then have a readonly public List eg:

public List<ComboBoxPair> MyPairs
{
    get
    {
        return myPairs;
    }
}

myPairs is a private List which I fill in the same way you are:

myPairs.Add(new ComboBoxPair(sqlReader.GetString[1], sqlReader.GetInt32[0]));

Now in my XAML I have

<ComboBox IsReadOnly="False" ItemsSource="{Binding MyPairs}" 
DisplayMemberPath="Text" SelectedValuePath="Index" 
SelectedValue="{Binding MyPairValue, Mode=TwoWay}" 
other values /> 

MyPairValue is the int Property which should hold the selected MedID.

Upvotes: 4

Related Questions