Search code examples
c#wpfdata-bindingwpfdatagrid

Bind List of Employee to DataGrid


I want to show Employee List data in the Data Grid. When I run below code empty grid is displayed.

XAML

<Window x:Class="SampleWpfApplication1.DataGridBindToEmployeeList"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataGridBindToEmployeeList" Height="300" Width="300" 
        xmlns:local="clr-namespace:SampleWpfApplication1.ViewModel">
    <Window.Resources>
        <local:EmployeeInfo x:Key="employeeInfo"/>
    </Window.Resources>
    <DataGrid ItemsSource="{Binding Source={StaticResource employeeInfo}}" AutoGenerateColumns="False" Height="300" Width="300" >
        <DataGridTextColumn Binding="{Binding Path=EmployeeId}" Header="Employee Id" Width="300"/>
        <DataGridTextColumn Binding="{Binding Path=EmployeeName}" Header="Employee Name" Width="300"/>
    </DataGrid>
</Window>

DataContext:

public class Employee
    {
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }
    }

    public class EmployeeInfo
    {
        public ObservableCollection<Employee> EmployeeList { get; set; }

        public EmployeeInfo()
        {
            EmployeeList = new ObservableCollection<Employee>();

            for (int i = 0; i < 3; ++i)
            {
                EmployeeList.Add(new Employee() { EmployeeId = i, EmployeeName = i.ToString() + "ABC" });
            }
        }
    }

Output Should Be:

Employee Id   | Employee Name
1             | 1ABC
2             | 2ABC
3             | 3ABC

Solution

  • Try this:

    <DataGrid ItemsSource="{Binding Source={StaticResource employeeInfo}, Path=EmployeeList}" AutoGenerateColumns="False" Height="300" Width="300" >
       <DataGrid.Columns>
          <DataGridTextColumn Binding="{Binding Path=EmployeeId}" Header="Employee Id" Width="300"/>
          <DataGridTextColumn Binding="{Binding Path=EmployeeName}" Header="Employee Name" Width="300"/>
       </DataGrid.Columns>
    </DataGrid>
    

    at the moment you set ItemsSource to whole EmloyeeInfo class and you want to point to your ObservableCollection<Employee>, also you forgot to wrap your column in DataGrid.Columns