In addition to my previous answer, since you prefer to indicate not to add the columns manually, I suggest you another option: using custom attributes in your properties definition.
First, you have to code your custom attribute:
MyPropertyAttribute class
[AttributeUsage(AttributeTargets.Property)]
public class MyPropertyAttribute : Attribute
{
public enum VisibilityOptions
{
visible,
invisible
}
private VisibilityOptions visibility = VisibilityOptions.visible;
public MyPropertyAttribute(VisibilityOptions visibility)
{
this.visibility = visibility;
}
public VisibilityOptions Visibility
{
get
{
return visibility;
}
set
{
visibility = value;
}
}
}
You could use it in your classes, just like this:
Foo class
public class Foo
{
private string name;
private string surname;
[MyPropertyAttribute(MyPropertyAttribute.VisibilityOptions.visible)]
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
[MyPropertyAttribute(MyPropertyAttribute.VisibilityOptions.invisible)]
public string Surname
{
get
{
return surname;
}
set
{
surname = value;
}
}
}
You could write a method, that iterates the properties in your binded objects, using reflection, and test if they are marked as visible or invisible, in order to add or don´t add columns. You could even have a custom DataGridView with this behavior, so you don´t have to repeat this everytime. You´ll only to use your custom DataGridView, and mark the visibility in the properties.
Something like this...
public class MyCustomDataGridView : DataGridView
{
public MyCustomDataGridView()
{
this.AutoGenerateColumns = false;
}
public void Load<T>(ICollection<T> collection)
{
foreach(object myAttribute in typeof(T).GetCustomAttributes(typeof(MyPropertyAttribute).GetType(), true))
{
if (((MyPropertyAttribute)myAttribute).Visibility == MyPropertyAttribute.VisibilityOptions.visible)
{
//...
}
}
}
}