DataGridView - display the value of an object in a column

I am binding some collection to a DataGridView . The collection contains KeyValuePair objects, where the key is a string and the value is an object of my Field class . The DataGridView displays two columns — one of which contains the key, and the other the value. The value ( Field ) is displayed using the ToString () method . But I would like it to be displayed using the Name property. The problem is that the column does not contain the DisplayMember property .
How can I do it?

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

+3
source share
2 answers

DataGridView(like most direct list-based bindings) can only be bound to the immediate properties of a row element. Could you create a facade object for this? that is, a class that takes an 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, can you create a new object? For example, data bindings work (at least read-only) with anonymous types:

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

Finally, you can hack in ComponentModelto flatten the model at runtime, but it really is not suitable for this.

+2
source

DataGridView (view.VirtualMode = true) CellValueNeeded (, , CellValuePushed), "". -, .

0

Source: https://habr.com/ru/post/1703727/


All Articles