Binding to BindingList<T> - choose what to bind?

sarsnake picture sarsnake · Jul 24, 2009 · Viewed 7.6k times · Source

Say I have an business object called Sample and I have BindingList of Samples. A sample has 4 properties.

Can I select which properties are bound to DataGrid or there no option to customize such a thing?

NOTE: I am using Compact Framework, where is NO DataGridView, as well as Autogenerate property and DataMember property.

Please keep this in mind while replying.

Answer

Justin Drury picture Justin Drury · Jul 24, 2009
BindingList<Sample> samples = new BindingList<Sample>();
DataGridView dgv = new DataGridView();
dgv.DataSource = samples;

This should display each public property as a column on the DataGridView. If you want to change which properties are displayed, you need to do the following as well:

dgv.AutoGenerateColumns = false;

and go into the properties of the datagridview, add the columns manually and set the DataPropertyName to the property name.

If you created the datagridview in code, the following will create and add a column to the dgv.

DataGridViewColumn dgvc = new DataGridViewColumn();
dgvc.Name = "PropertyA";
dgvc.HeaderText = "Property A";
dgvc.DataPropertyName = "PropertyA";
dgv.Columns.Add(dgvc);


EDIT

This SHOULD give you something closer to what you were wanting. However, because it uses an anonymous class, you can't use BindingList (that I know of). Alternativly, you can create a SampleBinding class that just has the properties you want to be displayed and generate those from the list of normal samples.

public class Sample
{
    public int PropertyA {get;set;}
    public bool PropertyB {get;set;}
    public string PropertyC {get;set;}
    public double PropertyD {get;set;}
}

List<Sample> samples = new List<Samples>(GetSamples());
var sampleBinding = from sample in samples
                    select new
                    {
                        PropertyA = sample.PropertyA,
                        PropertyC = sample.PropertyC
                    };

BindingList bl = new BindingList();
bl.DataSource = sampleBinding;
dgv.DataSource = bl;


EDIT 2

public class Sample
{
    [Browsable(false)]
    public int PropertyA {get;set;}
    public bool PropertyB {get;set;}
    public string PropertyC {get;set;}
    [Browsable(false)]
    public double PropertyD {get;set;}
}