简体   繁体   中英

List in PropertyGrid C#

I have an Employee class. There are many departments maintained in the database and an employee may only belong to a particular department.

public class Employee
{
    private string name;
    private int depID;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public int DepartmentID
    {
        get { return depID; }
        set { depID = value; }
    }
}

public class Department
{
    private int depID;
    private string depName;

    public int DepartmentID
    {
        get { return depID; }
    }

    public int DepartmentName
    {
        get { return depName; }
        set { depName = value; }
    }
}

How can I display the object Employee in the PropertyGrid with the department as a one of the properties that will be displayed as combobox?

Is it possible? Or is there any better implementation? Thanks in advance for your inputs.

I went ahead and drafted you up an experiment (for myself as well since I have never done this). It uses Linq for this particular solution to populate the combo box at hand, but I'm sure you could populate it other ways as well.

My documentation came from here under the subsection Adding Domain List and Simple Drop-down Property Support

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

public class Employee : StringConverter
{
    DataClasses1DataContext mydb = new DataClasses1DataContext();

    public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
    {
        return true;
    }

    public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
    {
        var a = (from u in mydb.Customers select u.CustomerID).ToArray();
        return new StandardValuesCollection(a);
    }

    public string Name { get; set; }

    [TypeConverter(typeof(Employee)), CategoryAttribute("Document Settings")]
    public string DepartmentID { get; set; }
}

On the form load I selected:

 private void Form1_Load(object sender, EventArgs e)
 {
     Employee temp = new Employee();
     propertyGrid1.SelectedObject = temp;
 }

I hope this is what you are looking for. It's worth noting that you may change StringConverter to TypeConverter if you'd like, but I used String becasue the field I'm dealing with is a string.

在此输入图像描述

您可以通过实现TypeConverter来实现

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