Binding List<T> to a DataGridView = DataGridView Empty

Binding List<T> to a DataGridView = DataGridView Empty

Post by admlangfor » Thu, 02 Oct 2008 12:54:03


Hi, I have a collection of objects which I am storing in a list

the object looks like this

struct Person
{
public int age;
public string name;
}

I then have a function (FunctionGetAllPeople) which returns a
List<Person> and all I am trying to do is bind the collection to the
DataGridView on a Windows Form

PersonDataGridView.DataSource = FunctionGetAllPeople();

Whenever I call the function it actually returns a collection of
people but my DataGridView on my Windows Form is never updated; it's
always empty....

Any suggestions appreciated!!
Thanks
Adam
 
 
 

Binding List<T> to a DataGridView = DataGridView Empty

Post by Marc Grave » Thu, 02 Oct 2008 14:57:22

First - data binding works on properties, not fields.
Second - for editable data, it will work much better on a class;
"Person" should *definitely* be a class, not a struct.

Try changing to:

public class Person {
public int Age {get;set;}
public string Name {get;set;}
}

(or in C# 2.0):

public class Person {
private int age;
public int Age {get {return age;} set {age = value;}}
private string name;
public string Name {get {return name;} set {name=value;}}
}

And it should work.

Marc

 
 
 

Binding List<T> to a DataGridView = DataGridView Empty

Post by admlangfor » Thu, 02 Oct 2008 15:34:55


Thanks!! I have since moved the object from a struct to a class and am
now using property set / get and it's working

Thanks again
Adam
 
 
 

Binding List<T> to a DataGridView = DataGridView Empty

Post by Marc Grave » Thu, 02 Oct 2008 15:59:47

No problem.

Just to reiterate: it is *very* rare to write a struct in C#. Most of
the time you should be writing classes. If in doubt, use a class (you
can always make it immutable if you want such behaviour).

Marc