简体   繁体   中英

Populating a C# / XAML combobox using EF and LINQ

I am currently creating a small test app and could do with a hand in relation to populating a drodown's list via Linq. I am getting a runtime error and I could really do with a pointer:

c#

egwEntities db = new egwEntities();
var sel = from o in db.dropdownsource select new {o.machine_desc};
TxtProductFamily.ItemsSource = sel;

xaml:

<ComboBox x:Name="TxtProductFamily" Text="{Binding testfield}" HorizontalAlignment="Left" Height="26" Margin="10,182,0,0" VerticalAlignment="Top" Width="319"/>

you need to do like this:

var sel = (from o in db.dropdownsource
           select o.machine_desc).ToList();

TxtProductFamily.ItemsSource = sel;

or More good will be to create a view model:

public class MyViewModel
{

public string MyText {get;set;}
public string MyValue {get;set;}

}

and then:

 var sel = (from o in db.dropdownsource
            select new MyViewModel{
                                   MyText = o.machine_desc,
                                   MyValue = o.SomeColumn
                                  }).ToList<MyViewModel>();

and :

<ComboBox x:Name="TxtProductFamily" Text="{Binding MyText}" HorizontalAlignment="Left" Height="26" Margin="10,182,0,0" VerticalAlignment="Top" Width="319"/>

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