views:

605

answers:

2

I have a class like this:

private class MyClass {
  [DisplayName("Foo/Bar")]
  public string FooBar { get; private set; }
  public string Baz { get; private set; }      
  public bool Enabled;
}

When I create a List<MyClass> and assign it to the DataSource of a DataGridView, the grid shows me two columns, "Foo/Bar" and "Baz". This is what I want to happen.

It currently works because Enabled is a field, not a property - DataGridView will only pick up properties. However, this is a dirty hack.

I would like to make Enabled a property too, but still hide it on the DataGridView.

I know I can manually delete the column after binding.. but that's not ideal.

Is there an attribute similar to DisplayName, that I can tag a property with? Something like [Visible(false)] ?

+6  A: 

[Browsable(false)]

C-Pound Guru
That's funny, in my eyes [Bindable(false)] should work and Browsable (according to the help) only defines if a property is shown in the PropertyGrid. But Bindable(false) is ignored by the DataGridView.
SchlaWiener
I agree, but after reading (and re-reading) the Framework Design Guidelines (http://www.amazon.com/Framework-Design-Guidelines-Conventions-Development/dp/0321246756), I have found that the designers didn't always follow their own rules (and sometimes did things that didn't make sense).
C-Pound Guru
+2  A: 

I've been blissfully unaware that the System.ComponentModel decorator attributes like BrowsableAttribute and it's kin were related to anything other than binding to a PropertyGrid. (facepalm) I like C-Pound Guru's approach because it allows you to keep your GUI more loosely coupled than what I've done in the past.

Just for a different perspective, the approach I've used for a long time is to pre-define columns in your DataGridView, either programatically or through the Form Designer. When you do this, you can set each column's DataPropertyName to the name of your property. The only trick is that you need to set the DataGridView's AutoGenerateColumns property to false otherwise the DGV will completely ignore your manually created columns. Note that, for whatever reason, the AutoGenerateColumns property is hidden from the Form Designer's Property Grid...no idea why. The one advantage I see to this approach is that you can pre-set the column formatting and such - you don't have to bind and then go tweak column rendering/sizing settings.

Here's an example of what I mean:

_DGV.AutoGenerateColumns = false;
DataGridViewTextBoxColumn textColumn = new DataGridViewTextBoxColumn();
textColumn.DataPropertyName = "FooBar";
textColumn.HeaderText = "Foo/Bar"; // may not need to do this with your DisplayNameAttribute
_DGV.Columns.Add(textColumn);
textColumn = new DataGridViewTextBoxColumn();
textColumn.DataPropertyName = "Baz";

List<MyClass> data = GetMyData();
_DGV.DataSource = data;
Yoopergeek