Is there an Attribute I can use in my class to tell DataGridView not to create a column for it when bound to a List

后端 未结 2 1202
花落未央
花落未央 2020-12-09 01:14

I have a class like this:

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


        
相关标签:
2条回答
  • 2020-12-09 01:35

    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;
    
    0 讨论(0)
  • 2020-12-09 01:53

    [Browsable(false)] will hide a property from a DataGridView.

    A visual designer typically displays in the Properties window those members that either have no browsable attribute or are marked with the BrowsableAttribute constructor's browsable parameter set to true. These members can be modified at design time. Members marked with the BrowsableAttribute constructor's browsable parameter set to false are not appropriate for design-time editing and therefore are not displayed in a visual designer. The default is true.

    0 讨论(0)
提交回复
热议问题