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.
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:Alternatively, you could project into a new object? For example, data-bindings work (read-only, at least) with anonymous types pretty well:
Finally, you can hack around in
ComponentModelto flatten the model at runtime, but it really isn’t worth it just for this.