views:

423

answers:

3

I am trying to bind a DataGridView to a List, where MyObject looks like

class MyObject
{
    public string Property1 { get; set; }
    public string Property2 { get; set; }
}

//List<MyObject> objects;
grid.Columns[0].DataPropertyName = "Property1";
grid.DataSource = objects;

I want only one property to be displayed, but instead I get another column added to my DataGridView where the Property2 is also displayed. How can I prevent it from being added?

+1  A: 

It sounds like you have the AutoGenerateColumns property of your DataGridView control set to True. You can either set it to False, or use the .Columns.Remove method to remove the column you don't want to see.

Robert Harvey
+3  A: 

If you never want that property displayed:

class MyObject
{
    public string Property1 { get; set; }
    [Browsable(false)]
    public string Property2 { get; set; }
}

Otherwise, as already stated - set AutoGenerateColumns to false and add them manually.

Marc Gravell
A: 

I believe you need to set up the columns manually, as Henk said. However you may want to set more properties than in his example. This is what I have done in a project:

DataGridView dataGridView = new DataGridView();
dataGridView.AutoGenerateColumns = false;

DataGridViewColumn columnA = new DataGridViewTextBoxColumn();
columnA.DataPropertyName = "propertyA";
columnA.HeaderText = "Column A";
columnA.Name = "columnA";

DataGridViewColumn columnB = new DataGridViewTextBoxColumn();
columnB.DataPropertyName = "propertyB";
columnB.HeaderText = "Column B";
columnB.Name = "columnB";

dataGridView.Columns.Clear();
dataGridView.Columns.Add(columnA);
dataGridView.Columns.Add(columnB);
dataGridView.AutoResizeColumns();

I believe the above works. If you get a weird exception check to be sure that the columns/cells have default cell styles defined.

emddudley