I am trying to display a DataTable onto a DataGrid which has two columns.
When I update the DataTable, the DataGrid shows new rows but the cells are empty. I have looked through many different possible solutions for this, and still have not been able to display the results.
Here is my xaml code for the DataGrid:
<DataGrid x:Name="SubjectsList" Height="500" ScrollViewer.CanContentScroll="True" AutoGenerateColumns="False" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Subject" Width="2*"/>
<DataGridTextColumn Header="Weekly" Width="*"/>
</DataGrid.Columns>
</DataGrid>
The following is my C# code for updating the table:
public void AddSubject(object sender, RoutedEventArgs e)
{
Subject temp = new Subject(SubjectName.Text, Convert.ToInt32(PerWeek.Text));
subjects.Add(temp);
MessageBox.Show(temp.Name + " has been added");
for(int i = 0; i < subjectsTable.Rows.Count; i++)
{
subjectsTable.Rows.RemoveAt(i);
}
foreach (Subject subject in subjects)
{
DataRow dataRow = subjectsTable.NewRow();
dataRow[0] = subject.Name;
dataRow[1] = subject.ClassesPerWeek;
subjectsTable.Rows.Add(dataRow);
MessageBox.Show(subject.Name);
}
SubjectsList.ItemsSource = subjectsTable.DefaultView;
}
In the above code, SubjectsList
is my DataGrid, and subjectsTable
is my DataTable.
I have tried the following:
- Use
DataGrid.DataContext
instead ofDataGrid.ItemSource
- Added
ItemSource = "{Binding Path=subjectsTable}"
in my xaml code - Tried to add the rows as items using
DataGrid.Items.Add(dataRow)
- Added a
getter
andsetter
method for each of the data members of my user-defined classSubject
- All of my variables, data members and data structures are public.
If anybody knows how to make the data visible, then please help me. Thank you.
Here is what happens after I have added two subjects: