Niall
Niall

Reputation: 1621

DGV DataSource displays Class name not value

I have a DataGridView being populated using CoolStorage (ORM) CSList class as its DataSource. It is displaying Contacts and it's the ContactType column that instead of displaying the underlying ContactTypeName just displays "ContactType" for every record.

I cannot change the value of that cell by stepping through the rows as it's data bound, although when hovering over DataSource I can see that it has the ContactTypeName is available as a property of ContactType.

Is there a way I can change what value is displayed in the ContactType cells (I'm thinking something like an equivalent to ComboBox's DisplayMember) without having to manually constuct a DataTable from my result set?

Many thanks.

Upvotes: 0

Views: 196

Answers (2)

Alex Filipovici
Alex Filipovici

Reputation: 32571

Have you considered using CSListGeneric instead of CSList?

You can then use System.Linq to select what you want to be displayed in the DataGridView:

class Program
{
    class ContactType
    {
        public string Name { get; set; }
    }
    class Contact
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public ContactType ContactType { get; set; }
    }
    static void Main(string[] args)
    {
        CSList<Contact> contacts = new CSList<Contact>();
        //add contacts to the list
        var x = from c in contacts
                select new {
                    c.Id,
                    c.Name
                    ContactTypeName=c.ContactType.Name
                };
    }
}

Upvotes: 1

D Stanley
D Stanley

Reputation: 152626

The only One way I know of to do it without setting up columns manually is to override the ToString() function of the ContactType class.

If you want to edit it, however, you'll need to set up the columns manually.

Just about every other grid UI I've worked on needed to have the colums set up manually for one reason or another.

Another alternative is to bind to a wrapper class (basically a ViewModel) that exposes the ContactName as a property rather than as a related object. You could even do two-way binding with that model.

Upvotes: 3

Related Questions