简体   繁体   中英

Show ToString of a Collection Wrapper Class in DataGridView

I have a class that has one of its properties being of type ObservableCollection<string>

public class SizeList
{
    public string ID { get; set; }

    public string Name { get; set; }

    //public ObservableCollection<string> List { get; set; }
    public ListEntryCollection List { get; set; }
}

During a unit test I return a list of SizeList and then show it in a DataGridView to check the results I am expecting, the data is fine but I am missing the field List in the DGV; only the ID and Name are shown, so I have made a wrapper class for the ObservableCollection<string> and overriden its .ToString() method:

namespace System.Collections.ObjectModel
{
    using System.Collections.Generic;

    public class ListEntryCollection : ObservableCollection<string>
    {
        public ListEntryCollection(IEnumerable<string> collection)
            : base(collection)
        {
        }

        public override string ToString()
        {
            return Count.ToString() + ((Count > 1) ? " Entries": " Entry");
        }
    }
}

But I am still not getting the List field in the DGV, so what am I doing wrong?

DGV 结果

Per Column Types in the Windows Forms DataGridView Control , the only property types for which bound columns are automatically generated are numbers, text, booleans, and images.

To display other types, you need to add the column manually to the DataGridView , or use a custom column type (and even then, you'll probably have to add it manually.)

A couple of options present themselves:

  • You could try adding a read-only property to SizeList to display the description of the list, and see if that will result in a column being automatically created.

  • You can try adding a column manually, which I believe you can do in the Form Designer if you click on the DataGridView . You will probably have to override a method or two, or use an event handler, in order to change the display from the default. (It's possible, though, that it will use the ToString override you created, in which case the problem is solved.)

  • Or, you could create a ListSummaryDataGridViewColumn class, that can represent a list by display a count of the items in it, and add one of those manually.

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