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

I have a ComboBox already populated, and all I want to do is set it to a specific selectedItem, knowing its value.

I am trying to do this, but nothing happens:

comboPublisher.SelectedValue = livre.Editeur; 

Given the fact that I already applied the Equals (..) method in my Editeur class, as follows:

  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:

  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; } 
+7
c # combobox
source share
4 answers

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

[Update] Instead of adding each item to your combobox directly, you should create a collection to store these 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
source share

Set the Text property.

+3
source share

You have created a new Equals implementation that hides an object in Object. Try declaring it with a public override bool and see if that helps.

+2
source share

Think that you should also implement IEquatable in the Editeur class, but pass the object as an argument. Something like that. 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; } 
0
source share

All Articles