Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

combobox

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;
        }
like image 542
Amokrane Chentir Avatar asked Mar 05 '10 01:03

Amokrane Chentir


3 Answers

Set the Text property.

like image 99
AMissico Avatar answered Nov 04 '22 14:11

AMissico


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";
like image 2
Anonymous Avatar answered Nov 04 '22 14:11

Anonymous


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.

like image 2
Dave Avatar answered Nov 04 '22 16:11

Dave