c# - How to show only certain columns in a DataGridView with custom objects -



c# - How to show only certain columns in a DataGridView with custom objects -

i have datagridview , need add together custom objects it. consider next code:

datagridview grid = new datagridview(); grid.datasource = objects;

with code datagridview object properties columns. in case, don't want show of information; want show 2 or 3 columns. know can set

autogeneratecolumns = false.

but not know how proceed afterwards. 1 alternative hide columns not involvement me, think improve in opposite way. how can this?

whenever create grid.datasource result of linq projection on objects.

so this:

grid.datasource = objects.select(o => new { column1 = o.somevalue, column2 = o.someothervalue }).tolist();

the nice thing can set autogeneratecolumns true, generate columns based on properties of projected objects.

edit:

the 1 downside approach projecting anonymous object, can have problems in situations need access specific object in click event, example.

in case may improve off defining explicit view model , projecting objects those. e.g.,

class myviewmodel { public int column1 { get;set; } public int column2 { get;set; } } grid.datasource = objects.select(o => new myviewmodel() { column1 = o.somevalue, column2 = o.someothervalue }).tolist();

edit 2:

myviewmodel represents of columns want display in datagridview. illustration properties should of course of study renamed suit doing. in general, point of viewmodel serve sort of converter mediates between model (in case list of objects) , view.

if wanting retain reference underlying object, best way might supply via constructor:

class myviewmodel { public int column1 { get;set; } public int column2 { get;set; } .... private sometype _obj; public myviewmodel(sometype obj) { _obj = obj; } public sometype getmodel() { homecoming _obj; } } grid.datasource = objects.select(o => new myviewmodel(o) { column1 = o.somevalue, column2 = o.someothervalue }).tolist();

the reason have gone getter method retrieve underlying model object avoid column beingness generated it.

c# datagridview

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -