Binding List<T> to a DataGridView = DataGridView Empty

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • admlangford@gmail.com

    Binding List<T> to a DataGridView = DataGridView Empty

    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 (FunctionGetAll People) which returns a
    List<Personand all I am trying to do is bind the collection to the
    DataGridView on a Windows Form

    PersonDataGridV iew.DataSource = FunctionGetAllP eople();

    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

  • Marc Gravell

    #2
    Re: Binding List&lt;T&gt; to a DataGridView = DataGridView Empty

    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

    Comment

    • admlangford@gmail.com

      #3
      Re: Binding List&lt;T&gt; to a DataGridView = DataGridView Empty

      On Oct 1, 3:57 pm, Marc Gravell <marc.grav...@g mail.comwrote:
      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

      Comment

      • Marc Gravell

        #4
        Re: Binding List&lt;T&gt; to a DataGridView = DataGridView Empty

        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

        Comment

        Working...