Putting list of objects into a datagridview

T

Tolgan

I have an object class "Person" say, with various public properties
including say "Name" and "Salary"

I have several person objects that I have created by some method outside the
scope of this discussion.

I want to setup a datagridview with each row corresponding to one person
object, and two columns being "Name" and "Salary". I want the user to be
able to click on the column heading to sort rows based on values in that
column. Users are not permitted to add to change rows, though can select
rows as operands to other operations.


This feels like it should be straightforward by setting up a collection of
persons as a datasource property either of the dataviewcontrol itself, or of
a bindingsource (which is then itself attached to the datagridview). However
whenever I go this route I seem to lose the (user) ability to sort on column
values.

Or, I can just add rows of {person.name, person.salary} pairs directly to
the datagridview but this is not very satisfactory as when the user selects
I want to get back the person object, not just the name and salary values.

What am I missing?
 
J

Joanna Carter [TeamB]

"Tolgan" <[email protected]> a écrit dans le message de (e-mail address removed)...

| What am I missing?

Create an instance of the BindingList<T> class, passing your list to the
constructor, then set the DataGridView to that as DataSource. You may also
need to write a Comparer<T> derived class to implement IComparer<T> to
achieve sorting.

Joanna
 
T

Tolgan

Gosh - a bit more programming than I expected to have to do given how nearly
the datagridview does it on its own without any datasource! But I've tried
your suggestion, certainly works and haven't come up with anything better,
so many thanks!

Chris (tolgan)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top