Click here to Skip to main content
15,884,859 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Suppose, I have the following DataGrid:
<DataGrid Name="customershowgrid"/>

How do I add the following list of objects to the customershowgrid DataGrid to display all the customer instances' attributes like name, phoneno etc.

What I have tried:

The following code generates empty rows and don't display any of the instances and/or their attributes:
List<AddCustomer.Customer> customers = new List<AddCustomer.Customer>()
{
    new AddCustomer.Customer()
    {
        _name="javed", _street="crib",
        _city="rwp", _state="punjab", 
        _phoneno="923340100321",
        _symptoms="none", _total="$399",
        _dateentered="2-Dec-2021"
    }
};
customershowgrid.ItemsSource = customers;
this.Show();
Posted
Updated 4-Dec-21 7:00am
v2
Comments
[no name] 3-Dec-21 14:09pm    
Does your Customer class contain "properties"?
Bill Joeden 4-Dec-21 1:38am    
yes it does like: public string name {get; set;} etc.
there are no compilation errors. it only does not show the output
BillWoodruff 4-Dec-21 0:36am    
see: https://stackoverflow.com/a/32258205/133321
Bill Joeden 4-Dec-21 1:43am    
from the code-behind, I think I have done that by doing:
this.customershowgrid.ItemsSource = customers;

The bound collection property has to be public, or it won't bind.

C#
public class MainWindow: Window, INotifyPropertyChanged
{
    // put your INotifyPropertyChanged implementation here
    //

    private ObservableCollection<AddCustomer.Customer> customers;
    public ObservableCollection<AddCustomer.Customer> Customers { get; set; }

    public MainWindow()
    {
        this.InitializeWindow();
        this.DataContext = this;
        this.Customers = new ObservableCollection<AddCustomer.Customer>()
        {
            new AddCustomer.Customer(){ /*set properties here*/ },
        };
     }
}


Set the ItemsSource in your XAML. You can use a List instead of an ObservableCollection, but if you do, you lose the ability of the GridView to update itself when the collection changes.
 
Share this answer
 
Comments
Bill Joeden 4-Dec-21 9:41am    
I don't want to implement INotifyPropertyChanged now. Can I use bind it with a list of instances of class that does not have INotifyPropertyChanged?
Based on your "field names" and your "property" reference (name {get;set;}) I would say you did not use the (private) "fields" as backing stores for the "properties", and you should be using "property names" in your initializer. i.e. new xxx() { name = "..." and NOT _name, etc. in this case.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900