Search code examples
c#objectlistview

How to bind ObjectListview header to an object?


I have single ObjectListview which should show different models while user is switching some controls. So using Form designer is not an option to set headers/columns. I need to switch them dynamically.

I know I can do it using AllColumns described here, delete and add again. But my question is can I do it through some object, just like I feed data to the list view? Then I would have different columns object alongside with data object and would switch them together.


Solution

  • If you look in the cookbook then Number 29 is probably what you are after. http://objectlistview.sourceforge.net/cs/recipes.html#can-i-generate-the-whole-objectlistview-directly-from-my-model
    (Below is taken from this source).

    There is a Generator class, to which you can pass your model and it will automatically create the columns based on the public properties.

    Generator.GenerateColumns(this.olv1, typeof(MyModelClass), true);
    

    You can even enhance your model by using OLVColumn attributes.

    public class MyClass {
    
        [OLVColumn(Width = 150)]
        public DateTime When { get; set; }
    
        [OLVColumn(DisplayIndex = 5, Width = 75, TextAlign = HorizontalAlignment.Right)]
        public decimal Rate { get; set; }
    
        [OLVColumn("From", DisplayIndex=1, Width = 50, TextAlign = HorizontalAlignment.Center)]
        public string FromCurrency { get; set; }
    
        [OLVColumn("To", DisplayIndex = 3, Width = 50, TextAlign = HorizontalAlignment.Center)]
        public string ToCurrency { get; set; }
    
        [OLVColumn("Amount", DisplayIndex = 2, AspectToStringFormat = "{0:C}", Width = 75, TextAlign = HorizontalAlignment.Right)]
        public decimal FromValue { get; set; }
    
        [OLVColumn("Amount", DisplayIndex = 4, AspectToStringFormat = "{0:C}", Width = 75, TextAlign = HorizontalAlignment.Right)]
        public decimal ToValue { get; set; }
    
        [OLVColumn(IsVisible = false)]
        public string UserId { get; set; }
    }