Search code examples
c#wpf

Items are showing blank in DataGrid


I have a TableData class:

public class TableData
{
    public string ID, WrestlerID;
    public string Name;
}

And some data that I then put on a list:

List<TableData> _tableData = new List<TableData>();
TableData tableData = new TableData
{
    ID = "0",
    WrestlerID = "000",
    Name = "test1"
};
_tableData.Add(tableData);
TableData tableData2 = new TableData
{
    ID = "1",
    WrestlerID = "111",
    Name = "test2"
};
_tableData.Add(tableData2);

I then iterate through my _tableData list and add each item on my DataGrid:

foreach (TableData data1 in _tableData)
{
    DGTable.Items.Add(data1);
}

BTW Here's my DataGrid:

<DataGrid x:Name="DGTable" Grid.Row="1">
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID" Binding="{Binding ID}" Width="100"/>
        <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="*"/>
        <DataGridTextColumn Header="Wrestler ID" Binding="{Binding WrestlerID}" Width="200"/>
    </DataGrid.Columns>
</DataGrid>

When I run the app, the DataGrid displays 2 rows but all fields are empty. Any thoughts? Thanks!


Solution

  • Your TableData class needs to have properties instead of fields to be able use bindings.

    It should also implement the INotifyPropertyChanged interface to use observable properties, so that changes to those properties get reflected in the UI.

    Change your class as follows:

    public class TableData : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;  
      
        private void OnPropertyChanged([CallerMemberName] String propertyName = "")  
        {  
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }  
    
        private string id;
        public string ID
        {
            get => id;
            set
            {
                if(id == value) return;
                id = value;
                OnPropertyChanged();
            }
        }
    
        // repeat for WrestlerID and Name
        //...
    }
    

    Don't forget to add using System.ComponentModel; at the top.