mark yer
mark yer

Reputation: 403

Add programmatically ListViewItem into Listview in WPF

So i have this Dictionary:

 Dictionary<string, double> _statistics;

Ans i want to add this Dictionary into my ListView with 2 columns:

DataTable table = new DataTable();
table.Columns.Add("Name");
table.Columns.Add("Percent");

foreach (KeyValuePair<string, double> item in _statistics)
    table.Rows.Add(item.Key, item.Value);
listView.ItemsSource = table;

And got an error:

Cannot implicitly convert type 'System.Data.DataTable' to 'System.Collections.IEnumerable'. An explicit conversion exists (are you missing a cast?)

Edit

I also try this:

public class MyItem
{
    public string Name{ get; set; }

    public double Percentage { get; set; }
}

        var gridView = new GridView();
        ipStatilistViewsticslistView.View = gridView;
        gridView.Columns.Add(new GridViewColumn
        {
            Header = "Name",
            DisplayMemberBinding = new Binding("Name")
        });
        gridView.Columns.Add(new GridViewColumn
        {
            Header = "Percent",
            DisplayMemberBinding = new Binding("Percent")
        });

        foreach (KeyValuePair<string, double> item in _statistics)
            listView.Items.Add(new MyItem { Name = item.Key, Percentage = item .Value}); 

And in this case all i can see is my 2 columns heards.

Upvotes: 0

Views: 949

Answers (1)

dkozl
dkozl

Reputation: 33364

ItemsControl.ItemsSource is of IEnumerable type and DataTable does not implement that interface. You need to use DataView instead

listView.ItemsSource = table.DefaultView;

or

listView.ItemsSource = new DataView(table);

EDIT

As for your second example you set view of ipStatilistViewsticslistView and populate listView with items. I'm guessing it's not the same ListView. Also you bind Percent column whilst name of the property is Percentage

Upvotes: 1

Related Questions