tags:

views:

44

answers:

2

Is it possible to use a primitive-typed Collection, such as List<long>, as the DataSource for a DataGridView?

After a half-hearted attempt to make it work, I gave in and created a simple struct so I could give DataGridViewColumn a PropertyName. But now I have to box my values when I deal with the UI, unbox them for the rest of my app (thus negating the benefits of data binding), and implement IComparable and IEquatable in my struct to support List sorting and searching (a simple enough task, the existence of the struct itself is cluttersome enough).

It seems like a while lot of overhead and clutter just to give a list of values to a UI widget. Surely there is an easier way...

+1  A: 

If you have a list of numbers that you want to show to the user consider using a ComboBox. This way you can set the DataSource to the List<long>.

However, if you really need the DataGridView you can change your List<long> to List<Long?> and you can now bind a grid view column to the Value property of the bounded list. This approach saves you the custom struct, but it's still a compromise solution.

João Angelo
Thanks, List<long?> should do just fine. I wasn't aware of nullable types.
PunctuallyChallenged
It's worth noting that the `Value` property of a nullable type is read-only, so the `DataGridView` cells cannot be edited using this workaround.
PunctuallyChallenged
A: 

@João's solution is nice if you have control over your code.

If you don't control the list coming in, you could wrap it in a linq expression in order to get a named entity to bind to.

List<int> list = new List<int> {1, 1, 1};
var q = from item in list select new { bindingname = item };
dataGridView1.DataSource = q.ToList();
Mikael Svenson
Interesting, thanks.
PunctuallyChallenged