Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide column of DataGridView when using custom DataSource?

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?

like image 853
mglog Avatar asked Aug 05 '11 18:08

mglog


People also ask

How do I hide columns in data grid?

To hide a column in the DataGrid programmatically DataMember property, which it assumes is already set. Add the new DataGridTableStyle object to the datagrid's table styles collection. Hide the column by setting its Width property to 0, specifying the column index of the column to hide.

How to hide column in datagridview c#?

To hide a column programmaticallySet the DataGridViewColumn. Visible property to false .


1 Answers

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;} 
like image 145
Algoman Avatar answered Sep 30 '22 14:09

Algoman