Shaul Zuarets
Shaul Zuarets

Reputation: 849

How to bind list of objects to datagrid?

First of all I have read all of the smilier questions and tried their answers. Nothing seems to work for me.

I created a class named student. Then I have loaded a list of student from a database.

Now, I wish to show this list in a datagrid. All I get is an empty table.. :(

What seems to be the problem? (I tried datacontext instead of itemSource)

My C# code:

public partial class MainWindow : Window
{
    public List<student> studentsList = new List<student>();
    public MainWindow()
    {
        try
        {
            InitializeComponent();
            Classes.studentManager stdManager = new Classes.studentManager();


            studentsList = stdManager.Select();

            this.dgStudents.DataContext = studentsList.ToList();

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

XAML code is as follows

 <DataGrid AutoGenerateColumns="False" Height="211" Name="dgStudents" Width="Auto" Margin="39,0,-33,-142" VerticalAlignment="Bottom" ItemsSource="{Binding}">
   <DataGrid.Columns>
     <DataGridTextColumn Header="birthDate" Width="175" Binding="{BindingfirstName}" />
    </DataGrid.Columns>
   </DataGrid>

This is student object

  public class student
  {

    public int ID;
    public string firstName;
    public string lastName;
    public string studentID;
    public string homePhone;
    public string cellPhone;
    public string parentsPhone;
    public string parentsName;
    public string adress;
    public bool isPicFormExists;
    public string medProblems;
    public bool isParentsConfExists;
    public List<Class> classesList;
    public DateTime birthDate;
    public List<payments> payments;
    public double accountBalance;


    public student() 
    {
        try
        {

        }
        catch (Exception ex)
        {
            //TO-DO
        }
    }

}

Upvotes: 3

Views: 740

Answers (1)

Andrey Gordeev
Andrey Gordeev

Reputation: 32549

You need to define public properties in your student class. You cannot bind to fields.

WPF supports binding to properties of an object, not fields.

See this question for more info: Has it ever been possible to bind to a field in WPF?

Upvotes: 5

Related Questions