سؤال

I can't believe how difficult this simple task is.

I have the following code:

cboCountry.ValueMember = "ID";
cboCountry.DisplayMember = "Title";
var countries = from c in context.Set<sc_Countries>()
                orderby c.Title
                select new { c.ID, c.Title };

Now, I want to populate the ComboBox cboCountry with this collection, and then I want to select the list item with the ID (value) "US".

I was able to add the items to the ComboBox using cboCountry.Items.AddRange(countries.ToList()), but then cboCountry.SelectedValue = "US" had no effect.

Next, I tried adding the collection using cboCountry.DataSource = countries but this just left the control list empty.

Surely there must be a simple way to accomplish this trivial task. Can anyone offer the missing ingredient?

هل كانت مفيدة؟

المحلول

Until you call ToList() on your LINQ statement, you're not actually getting data from the database:

var countries = (from c in context.Set<sc_Countries>()
                 orderby c.Title
                 select new { c.ID, c.Title }).ToList();

Now you should be able to set the DataSource, etc. like you were:

cboCountry.ValueMember = "ID";
cboCountry.DisplayMember = "Title";
cboCountry.DataSource = countries;
cboCountry.SelectedValue = "US"

Edit:

Now that I'm re-reading your question, it looks like you were already calling countries.ToList(), but using Items.AddRange. I see the same thing you do when I try it. It appears you have to set the DataSource instead of using Items.AddRange, for SelectedValue to work.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top