gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:07:27 24 4
gpt4 key购买 nike

我使用下面的代码将项目添加到组合框,但无法弄清楚如何在 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)列表,例如:

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

myPairs 是一个私有(private)列表,我的填写方式与您相同:

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 属性。

关于c# - 组合框中的显示和值成员 c# wpf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45923909/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com