3

I have a class called Name with one property.

public class Name
{
    public string comboName { get; set; }
}

I'm attempting to run a LINQ query to return all FullName, and then create an instance of the Name class for each, assigning FullName to the property comboName. The instances are added to a List, and then I want List values to be added to ComboBox1 drop down values. Below is the code I've written so far.

void ComboBox1_Loaded(object sender, RoutedEventArgs e)
{
    GiftIdeasDataContext dc = new GiftIdeasDataContext();

    var qry = from r in dc.Recipients
                select new Name()
                {
                    comboName = r.FullName
                };

    List<Name> lst = qry.ToList();
    ComboBox1.ItemsSource = lst;
}

Issue: When the code is executed the ComboBox1 drop down only shows the string 'myMemory.Name' 9 times (the number of names which are in the Recipient table). Should I just create a list and assign string values to the list instead of using a class?

I've only been using the console window with c# up to now, this is my first project using WPF, so any help is appreciated.

luke_t
  • 2,935
  • 4
  • 22
  • 38
  • 2
    See this question http://stackoverflow.com/questions/561166/binding-wpf-combobox-to-a-custom-list ..Also have a look at DisplayMemberPath, SelectedValuePath for combobox – Amitd Aug 09 '15 at 10:26
  • When you debug, what do you see in `lst` if you put a breakpoint on the line `ComboBox1.ItemSource = lst;` – scgough Aug 09 '15 at 10:26
  • The list contains 9 values which are 'myMemory.Name'.. if I click the index drop down it shows `comboName` and then the actual value which I would expect to see. – luke_t Aug 09 '15 at 10:34

3 Answers3

2

The ComboBox needs to know how you want instances of your Name class displayed. As you didn't explicitly tell it, it uses Name.ToString() to display your Name instances.

You can explicitly tell the ComboBox how to display instances of your Name class through setting ComboBox1.DisplayMemberPath to comboName.

FlyingFoX
  • 3,379
  • 3
  • 32
  • 49
1
List<Name> lst= from r in dc.Recipients
                select new Name()
                {
                  comboName = r.FullName
                }.ToList<Name>();

or you can convert like the following :

List<Name> lst = (List<Name>)qry.ToList();
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
0
var lst = dc.Recipients.Select(r => new Name{ comboName = r.FullName }).ToList();
Kevin P.
  • 401
  • 4
  • 13