runtime binding to list of user defined object

What is the correct way to bind a datagridview to a homogenous list of objects at runtime. The datagridview should display 3 columns for each of the public members of the object using the example below.

...

Public List <names> namelist;

...

Class names

{

// properties

public string fname;

public string middle;

public string lname;

// methods

// .....

}



Answer this question

runtime binding to list of user defined object

  • David N.4117

    You could create

    BindingList<users> theUsers = new BindingList<users>();

    theUsers.Add(new users("John", "E.", "Doe"));

    and do a DataGridView.DataSource = theUsers.

    The grid will show column names "fname", "middle", and "lname" because default data binding behavior uses reflection to get all the public property names on your object (b.t.w, those fields should be wrapped in properties).

    To get more 'friendly' column names to appear in the datagrid, you can decorate your properties with attributes found in the System.ComponentModel namespace, like:

    [System.ComponentModel.DisplayName("First Name"), System.ComponentModel.Browsable(true)]
    public string FName
    {get/set ....}

    For even more control you can have your users object implement ICustomTypeDescriptor and INotityPropertyChanges interfaces.


  • Dancer

    Thanks. Just what I was looking for.
  • runtime binding to list of user defined object