[英]Display and Value Member in combobox c# wpf
我正在使用下面的代碼將項目添加到組合框中,但是無法計算出如何在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());
}
}
我處理此類組合框的方式是通過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是應該保存所選MedID的int屬性。
正確的方法是@JonathaWillcock的答案。
但是這里是最小的更改,以了解其工作原理:
XAML
<ComboBox DislayMemberPath="MedName" SelectedValuePath="MedID" ... />
在代碼中,更改循環:
while (sqlReader.Read())
comboBox_select_Item.Items.Add(new {
MedName = sqlReader["MedName"].ToString(),
MedID = sqlReader["MedID"].ToString()
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.