组合框c#wpf中的显示和值成员

时间:2017-08-28 16:54:31

标签: c# wpf data-binding combobox

我使用下面的代码将项目添加到组合框中,但是无法解决如何在WPF中添加显示和值成员的问题。我尝试过使用

DisplayMemberPath = MedName

和ValueMemberPath = MedID,但它仍然只使用MedName

非常感谢任何帮助。

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());
                }
            }

2 个答案:

答案 0 :(得分:1)

我处理这种组合框的方式是通过ComboBoxPair类:

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

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

然后我有一个只读的公开名单,例如:

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

myPairs是一个私人列表,我用同样的方式填写:

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

现在我的XAML中有

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

MyPairValue是int属性,它应该包含选定的MedID。

答案 1 :(得分:1)

正确的方式是@JonathaWillcock回答。

但是这里有最小的变化,看看它是如何工作的:

XAML

<ComboBox DislayMemberPath="MedName"  SelectedValuePath="MedID"  ... />
在代码中

,更改循环:

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