Binding List<T> to a DataGridView = DataGridView Empty

A

admlangford

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
 
M

Marc Gravell

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
 
A

admlangford

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

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
 
M

Marc Gravell

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
 

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