简体   繁体   English

DataGridView - 在列中设置对象的显示值

[英]DataGridView - setting object's displayed value in a column

I bind some collection to a DataGridView .我将一些集合绑定到DataGridView Collection contains KeyValuePair objects where key is a string and value is an object of my class Field .集合包含KeyValuePair对象,其中键是字符串,值是我的 class字段的 object 。 DataGridView displays two columns - one containing the key and the other one containing the value. DataGridView显示两列 - 一列包含键,另一列包含值。 The value ( Field object) is displayed with its ToString () method.值( Field对象)与其ToString () 方法一起显示。 But I would like it to be displayed using its Name property.但我希望使用它的 Name 属性来显示它。 The problem is the column contains no DisplayMember property.问题是该列不包含DisplayMember属性。
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.编辑:我知道我可以覆盖 ToString() 以返回 object 的名称,但我不想这样做。

DataGridView (in common with most direct list-based bindings) can only bind to immediate properties of the row item. DataGridView (与大多数直接基于列表的绑定一样)只能绑定到行项的直接属性。 You could perhaps create a facade object for this?您也许可以为此创建一个外观 object? ie a class that accepts the instance and returns the name as a direct property:即接受实例并将名称作为直接属性返回的 class :

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

Alternatively, you could project into a new object?或者,您可以投影到新的 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.最后,您可以在ComponentModel中修改以在运行时展平 model,但仅仅为此并不值得。

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.您可以将 DataGridView 置于虚拟模式 (view.VirtualMode = true),并处理 CellValueNeeded(可能还有 CellValuePushed)事件以访问“Name”属性。 This would avoid creating lots of wrapper objects, but does make the code somewhat less elegant.这将避免创建大量包装对象,但确实会使代码不那么优雅。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM