C# – How to hide column of DataGridView when using custom DataSource

cdatagriddatagridviewdatagridviewcolumnnet

I have a small app in c#, it has a DataGridView that gets filled using:

grid.DataSource = MyDatasource array;

MyClass hold the structure for the columns, it looks something like this:

class MyDatasource
{
    private string column1;        
    private string column2;

    public MyDatasource(string arg1, string arg2)
    {
        this.column1 = arg1;
        this.column2 = arg2;
    }

    public string column1
    {
        get
        {
            return this.column1;
        }
        set
        {
            this.column1 = value;
        }
    }

    public string column2
    {
        get
        {
            return this.column2;
        }
        set
        {
            this.column1 = value;
        }
    }
}

Everything works fine and the DataGridView gets populated with the correct data, but now I want to hide the column2. I tried adding [Browsable(false)] above the column declaration, that will hide it, but I also need to access the column value from code, and when I use [Browsable(false)] and try to read the content it acts like if the column doesn't exist. If I don't use it I can read the column without problem but it's visible in the DataGridView.

How could I hide the column but still be able to read its content from code?

Best Answer

In some cases, it might be a bad idea to first add the column to the DataGridView and then hide it.

I for example have a class that has an NHibernate proxy for an Image property for company logos. If I accessed that property (e.g. by calling its ToString method to show that in a DataGridView), it would download the image from the SQL server. If I had a list of Company objects and used that as the dataSource of the DataGridView like that, then (I suspect) it would download ALL the logos BEFORE I could hide the column.

To prevent this, I used the custom attribute

 [System.ComponentModel.Browsable(false)]

on the image property, so that the DataGridView ignores the property (doesn't create the column and doesn't call the ToString methods).

 public class Company
 {
     ...
     [System.ComponentModel.Browsable(false)]
     virtual public MyImageClass Logo { get; set;}
Related Topic