简体   繁体   English

DataGridView绑定到对象的“ ToString”属性

[英]DataGridView binding to an object's “ToString” property

I am binding a list of objects to a Winform DataGridView. 我将对象列表绑定到Winform DataGridView。 This works fine and has a column for each property on my object. 这工作正常,并且在对象上为每个属性都有一列。 I have now overridden the “ToString” on the object that outputs text based on the properties. 我现在已经覆盖了基于属性输出文本的对象上的“ ToString”。 I would now like to change my DataGridView so that it has a single column that binds to the “ToString” property of my object. 我现在想更改DataGridView,使其具有绑定到对象的“ ToString”属性的单个列。 Is this possible, as so far I've not found a way to do this. 这可能吗,到目前为止我还没有找到一种方法来做到这一点。

as far as I know binding works with properties, so you need to create property in your class, which will return result of ToString() : 据我所知,绑定适用于属性,因此您需要在类中创建属性,这将返回ToString()结果:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public string Text { get { return ToString(); } }

    public override string ToString()
    {
        return String.Format("{0}, {1} years", Name, Age);
    }
}

and here a way to force grid to NOT create columns for anything except Text property: 这是一种强制网格不为Text属性之外的任何内容创建列的方法:

grid.Columns.Add(new DataGridViewTextBoxColumn() {DataPropertyName = "Text", HeaderText = "Custom ToString value"});
grid.AutoGenerateColumns = false;

binding: 捆绑:

var people = new List<Person>()
    {
        new Person() {Name = "A", Age = 20},
        new Person() {Name = "B", Age = 30},
    };
grid.DataSource = people; 

I managed to fix this by following this link: Binding List Of String 我设法通过以下链接解决此问题: 字符串绑定列表

The solution was to wrap each string so that the binding mechanism knew what to bind. 解决方案是包装每个字符串,以便绑定机制知道要绑定的内容。

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

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