Search code examples
c#datagridviewattributesdatagridviewcolumn

Using an attribute to specify a columns FillWeight


I have a DataGridView that I am populating with a BindingList. The BindingList is a list of type SyncDetail which has a number of properties. In these properties I can use attributes to decide whether to not display a column (Browsable(false)), the display name of the column (DisplayName("ColumnName")) etc. See below for an example:

public class SyncDetail : ISyncDetail
{

    // Browsable properties

    [DisplayName("Sync Name")]
    public string Name { get; set; }

    // Non browsable properties

    [Browsable(false)]
    [XmlIgnore]
    public bool Disposed { get; set; }
}

Is there a way that I can use an attribute to define what the column width should be set at? e.g. [ColumnWidth(200)]. I would like to set the FillWeight if possible as my AutoSizeColumnsMode is set to Fill.

Thanks.


Solution

  • I ended up implementing a custom attribute to do this.

    public class ColumnWeight : Attribute
        {
            public int Weight { get; set; }
    
            public ColumnWeight(int weight)
            {
                Weight = weight;
            }
    }
    

    And then I can just override the OnColumnAdded method of my DataGridView to grab the attribute and set the FillWeight for the column.

    protected override void OnColumnAdded(DataGridViewColumnEventArgs e)
    {
        // Get the property object based on the DataPropertyName of the column
        var property = typeof(SyncDetail).GetProperty(e.Column.DataPropertyName);
        // Get the ColumnWeight attribute from the property if it exists
        var weightAttribute = (ColumnWeight)property.GetCustomAttribute(typeof(ColumnWeight));
        if (weightAttribute != null)
        {
            // Finally, set the FillWeight of the column to our defined weight in the attribute
            e.Column.FillWeight = weightAttribute.Weight;
        }
        base.OnColumnAdded(e);
    }
    

    Then I can just set the attribute on my properties of my object.

    public class SyncDetail : ISyncDetail
    {
    
        // Browsable properties
    
        [DisplayName("Sync Name")]
        [ColumnWeight(20)]
        public string Name { get; set; }
    
        etc...
    }