0

I want to be able to select the columns that are displayed in my DataGridView. I.e., I have a linq query that returns an IEnumerable but I don't want to display all the properties of Policy - I want to allow the user to choose what to display. So I thought something like this might work to create a "narrower" object with only the columns I want.

IEnumerable<Policy> policies = repository.GetPolicies();
var results = from p in policies select new {
    if (userPicked("PropertyOne")) PropertyOne = p.PropertyOne,
    if (userPicked("PropertyTwo")) PropertyTwo = p.PropertyTwo,
    ...
};
dataGridView1.DataSource = results;

Is there an elegant way to do this?

Part 2: Why does this work:

IEnumerable<Policy> policies = repository.GetPolicies();
dataGridView1.DataSource = policies;

but this doesn't:

IEnumerable<Policy> policies = repository.GetPolicies();
var results = from p in policies select p;
dataGridView1.DataSource = results;

In the second case nothing is displayed in the grid.

1 Answer 1

3

Use Dynamic Linq if you need to select fields dynamically. It contains a Select extension method that accepts a string of fields, so you can decide which fields to select at runtime:

public static IQueryable Select(this IQueryable source,    
       string selector, params object[] values);

Example of usage:

var products = db.Products
    .Where(condition)
    .OrderBy("Name")
    .Select(" new (ItemId,Name,Model,onsale)");

Part 2: Your grid is expecting a bindable interface such as IList, but the second code example returns an IQueryable. You can convert it to an IList by calling ToList().

var results = (from p in policies select p).ToList();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.