C# - 如何设置一个ComboBox selectedItem从特定的值? [英] C# - How to set a ComboBox selectedItem from specific value?
问题描述
我已经填充了ComboBox,我想做的是将其设置为一个特定的selectedItem知道它的值。
I have this already populated ComboBox and all I want to do is to set it to a specific selectedItem knowing its value.
我试着这个,但没有发生:
I'm trying this, but nothing happens:
comboPublisher.SelectedValue = livre.Editeur;
$ b <
Considering the fact that I already implemented Equals(..) method in my class Editeur, this way:
public bool Equals(IEditeur editeur)
{
return (this.Nom == editeur.Nom);
}
这是我填充我的ComboBox:
This is how I populate my ComboBox:
foreach (Business.IEditeur editeur in _livreManager.GetPublishers())
{
comboPublisher.Items.Add(editeur);
}
有什么想法吗?
谢谢!
:这似乎适用于:
comboPublisher.SelectedItem = livre.Editeur;
我的Equals方法是:
My Equals method is:
public override bool Equals(object obj)
{
IEditeur editeur = new Editeur();
if (!(obj is System.DBNull))
{
editeur = (IEditeur)obj;
return (this.Nom == editeur.Nom);
}
return false;
}
推荐答案
c $ c> DataSources 如果是WinForm / ItemsSource
在WPF的情况下你的cobobox然后你可以正确使用SelectedValue。
You need to set DataSources
in case of WinForm / ItemsSource
in case of WPF to your cobobox then you can use SelectedValue properly.
不要将每个项目直接添加到组合框中,而是创建集合来保存这些项目,然后将它设置为您的DataSource(WinForm)/ ItemsSource(WPF)
[Update] Instead of add each item to your combobox directly, you should create collection to hold those items and then set it as your DataSource (WinForm) / ItemsSource (WPF)
foreach (Business.IEditeur editeur in _livreManager.GetPublishers())
{
//comboPublisher.Items.Add(editeur);
list.Add(editeur);
}
combobox.ItemsSource = editeur;
combobox.SelectedValuePath = "value_property_name";
combobox.DisplayMemberPath = "display_property_name";
这篇关于C# - 如何设置一个ComboBox selectedItem从特定的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!