简体   繁体   中英

Entity Framework - Bind Combobox to Normalised Table Field

I am currently trying to bind an entity to a form however I want to have DataConfidenceLevel (see below) bound to a combobox with ConfidenceDescription as the display member. What is the correct way to populate the combobox?

(I am currently using WPF but a Winforms answer is acceptable)

Thanks

Entity Designer http://img19.imageshack.us/img19/374/entity.png

You want to bind a collection to a control and have a releated entity - namely navigation property DataConfidenceLevel of type DataConfidenceLevel - as the display member?

That is usually achieved really simple by overriding ToString(),

public partial class DataConfidenceLevel
{
   public override String ToString()
   {
      return this.ConfidenceDescription;
   }
}

and than setting DisplayMember to the DataConfidenceLevel property of the entity you want to bind.

The answer was simpler than I was expecting.

    comboBox.DataBindings.Add(new Binding("SelectedItem", this.dataBindingSource, "DataConfidenceLevel", true));
    comboBox.DataSource = db.DataConfidenceLevel;
    comboBox.DisplayMember = "ConfidenceDescription";
    comboBox.ValueMember = "ConfidenceLevelID";

I wrote two blog entries about one approach to handling this situation - it applies to ASP.net, but it might help you out.

Here are the posts, the first one is more of an introduction to the problem, the second entry shows how to pin it all together.

I'm not sure whether this qualifies as "the correct way" but it's certainly an approach:) I'd be happy to hear back if this helps you out!

Edit: After reading danbruc's answer, you can certainly override ToString on the Navigation property as he has suggested (for read only), but that's only a partial answer.

This won't work unless your LINQ query contains the "Include" statement, eg

var listOfThings = (from t in db.Thingy
                    .Include("DataConfidenceLevel")
                    select t).ToList();

Omitting the.Include() means that nothing will get bound to the column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM