简体   繁体   中英

DataGridView binding to an object's “ToString” property

I am binding a list of objects to a 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. I would now like to change my DataGridView so that it has a single column that binds to the “ToString” property of my object. 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() :

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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