views:

684

answers:

3

I bind some collection to a DataGridView. Collection contains KeyValuePair objects where key is a string and value is an object of my class Field. DataGridView displays two columns - one containing the key and the other one containing the value. The value (Field object) is displayed with its ToString() method. But I would like it to be displayed using its Name property. The problem is the column contains no DisplayMember property.
How can i do it?

Edit: I know I could override ToString() to return the name of the object but I don't want to do that.

+1  A: 

DataGridView (in common with most direct list-based bindings) can only bind to immediate properties of the row item. You could perhaps create a facade object for this? i.e. a class that accepts the instance and returns the name as a direct property:

public string Name {
    get {return innerObject.Name;}
    set {innerObject.Name = value;}
}
// snipped: other properties - Key etc

Alternatively, you could project into a new object? For example, data-bindings work (read-only, at least) with anonymous types pretty well:

grid.DataSource = originalData.Select(x=>
    new {x.Key, Name = x.Field.Name}).ToList();

Finally, you can hack around in ComponentModel to flatten the model at runtime, but it really isn't worth it just for this.

Marc Gravell
yeah i know it just shouldn't be used like this - i mean datagridview should simply display the property of the object in a column, but i hoped there was some way to handle it.
agnieszka
A: 

See also this question

jan
A: 

You could put the DataGridView into virtual mode (view.VirtualMode = true), and handle the CellValueNeeded (and possibly the CellValuePushed) events to access the "Name" property. This would avoid creating lots of wrapper objects, but does make the code somewhat less elegant.

JaredReisinger