Sukanya1991
Sukanya1991

Reputation: 776

DataGridView Add Multiple Rows for List in List Object

I have two classes Employee and Department as follows

class Employee
{
    public string ID {get;set;}
    public string Name {get;set;}
    public List<Departments> AssociatedDepartment {get;set;}
}

class Department
{
   public string DepartmentID {get;set;}
   public string DepartmentName {get;set;}
}

I am binding a DataGridView with List<Employee>. It is showing list of Employees but not Department of the employees.

List<Employee> employeeList = GetEmployeeList();

if (employeeList != null)
{
     grdResponse.DataSource = employeeList;
}

Now it is showing following data.

ID  Name  
---------
1   Joe  
2   Tim

What should I do to get following?

ID  Name Department 
--------------------
1   Joe  Software
1   Joe  Management
2   Tim  Hardware

Upvotes: 0

Views: 652

Answers (2)

ASh
ASh

Reputation: 35646

you can extend Employee class with get-only property (the column will be ReadOnly)

class Employee
{
    public string ID { get; set; }
    public string Name { get; set; }

    public string Departments
    {
        get 
        { 
           if (AssociatedDepartment == null || AssociatedDepartment.Count == 0)
              return string.Empty;
           return string.Join(", ", AssociatedDepartment.Select(d => d.DepartmentName));
        }
    }

    public List<Department> AssociatedDepartment { get; set; }
}

Upvotes: 1

Bioukh
Bioukh

Reputation: 1968

Add the following property in Employee :

public string Department
{
    get
    {
        string departments = string.Empty;
        foreach (Department department in AssociatedDepartment)
        {
            if (departments.Length != 0)
                departments += ", ";
            departments += department.DepartmentName;
        }
        return departments;
    }
}

Upvotes: 1

Related Questions