C# - How to set a ComboBox selectedItem from specific value?

时光总嘲笑我的痴心妄想 提交于 2019-12-23 08:49:49

问题


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;

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

This is how I populate my ComboBox:

foreach (Business.IEditeur editeur in _livreManager.GetPublishers())
        {
            comboPublisher.Items.Add(editeur);
        }

Any idea ?

Thanks !

[EDIT]: This seems to work with :

comboPublisher.SelectedItem = livre.Editeur;

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

回答1:


You need to set DataSources in case of WinForm / ItemsSource in case of WPF to your cobobox then you can use SelectedValue properly.

[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";



回答2:


Set the Text property.




回答3:


you've created a new implementation of Equals that hides the one in Object. Try declaring it with public override bool and see if that helps.




回答4:


In think that you have also to implement IEquatable in Editeur class, but passing an object as argument. Something like this. The rest of your code is fine.

public bool Equals(Editeur other)
{
    return (this.Nom == other.Nom);            
}

public override bool Equals(object obj)
{
    if (obj is Editeur)
    {
        return Equals(obj as Editeur);
    }
    return false;
}


来源:https://stackoverflow.com/questions/2384009/c-sharp-how-to-set-a-combobox-selecteditem-from-specific-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!